'use client'

import { useState, useEffect, useCallback } from 'react'
import {
  Search,
  Ticket,
  Clock,
  Loader2,
  Eye,
  RefreshCcw,
  ChevronLeft,
  ChevronRight,
  Send,
  MessageSquare,
  AlertCircle,
  CheckCircle2,
  Timer,
  User,
  XCircle,
} from 'lucide-react'
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card'
import { Button } from '@/components/ui/button'
import { Badge } from '@/components/ui/badge'
import { Input } from '@/components/ui/input'
import { Label } from '@/components/ui/label'
import { Textarea } from '@/components/ui/textarea'
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from '@/components/ui/select'
import {
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableHeader,
  TableRow,
} from '@/components/ui/table'
import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogFooter,
  DialogHeader,
  DialogTitle,
} from '@/components/ui/dialog'
import { Skeleton } from '@/components/ui/skeleton'
import { Separator } from '@/components/ui/separator'
import { ScrollArea } from '@/components/ui/scroll-area'
import { useToast } from '@/hooks/use-toast'
import { api } from '@/lib/api'

// ── Types ──────────────────────────────────────────────────────────────────────

interface TicketUser {
  id: string
  name: string
  email: string
  phone: string
}

interface TicketReply {
  id: string
  ticketId: string
  userId: string
  message: string
  isAdmin: boolean
  createdAt: string
  user?: TicketUser
}

interface Ticket {
  id: string
  userId: string
  subject: string
  description: string
  status: string
  priority: string
  assignedTo: string | null
  createdAt: string
  updatedAt: string
  user: TicketUser
  replies?: TicketReply[]
  _count?: { replies: number }
}

interface TicketSummary {
  open: number
  inProgress: number
  resolved: number
  avgResolutionTime: string
}

// ── Constants ──────────────────────────────────────────────────────────────────

const statusBadgeColors: Record<string, string> = {
  OPEN: 'bg-blue-100 text-blue-800 dark:bg-blue-900/40 dark:text-blue-400',
  IN_PROGRESS: 'bg-amber-100 text-amber-800 dark:bg-amber-900/40 dark:text-amber-400',
  RESOLVED: 'bg-emerald-100 text-emerald-800 dark:bg-emerald-900/40 dark:text-emerald-400',
  CLOSED: 'bg-gray-100 text-gray-800 dark:bg-gray-800/40 dark:text-gray-400',
}

const statusDotColors: Record<string, string> = {
  OPEN: 'bg-blue-500',
  IN_PROGRESS: 'bg-amber-500',
  RESOLVED: 'bg-emerald-500',
  CLOSED: 'bg-gray-400',
}

const statusLabels: Record<string, string> = {
  OPEN: 'Open',
  IN_PROGRESS: 'In Progress',
  RESOLVED: 'Resolved',
  CLOSED: 'Closed',
}

const priorityBadgeColors: Record<string, string> = {
  LOW: 'bg-slate-100 text-slate-800 dark:bg-slate-800/40 dark:text-slate-400',
  MEDIUM: 'bg-blue-100 text-blue-800 dark:bg-blue-900/40 dark:text-blue-400',
  HIGH: 'bg-orange-100 text-orange-800 dark:bg-orange-900/40 dark:text-orange-400',
  URGENT: 'bg-red-100 text-red-800 dark:bg-red-900/40 dark:text-red-400',
}

// ── Helpers ────────────────────────────────────────────────────────────────────

function formatDate(dateStr: string): string {
  return new Date(dateStr).toLocaleDateString('en-US', {
    year: 'numeric',
    month: 'short',
    day: 'numeric',
  })
}

function formatDateTime(dateStr: string): string {
  return new Date(dateStr).toLocaleDateString('en-US', {
    year: 'numeric',
    month: 'short',
    day: 'numeric',
    hour: '2-digit',
    minute: '2-digit',
  })
}

// ── Component ──────────────────────────────────────────────────────────────────

export default function TicketsView() {
  const { toast } = useToast()

  // List state
  const [tickets, setTickets] = useState<Ticket[]>([])
  const [summary, setSummary] = useState<TicketSummary | null>(null)
  const [loading, setLoading] = useState(true)
  const [error, setError] = useState<string | null>(null)
  const [page, setPage] = useState(1)
  const [totalPages, setTotalPages] = useState(1)

  // Filters
  const [statusFilter, setStatusFilter] = useState('all')
  const [priorityFilter, setPriorityFilter] = useState('all')
  const [searchQuery, setSearchQuery] = useState('')

  // Detail dialog
  const [detailOpen, setDetailOpen] = useState(false)
  const [selectedTicket, setSelectedTicket] = useState<(Ticket & { replies: TicketReply[] }) | null>(null)
  const [detailLoading, setDetailLoading] = useState(false)

  // Reply form
  const [replyMessage, setReplyMessage] = useState('')
  const [replying, setReplying] = useState(false)

  // Status update
  const [updatingStatus, setUpdatingStatus] = useState(false)

  const fetchTickets = useCallback(async () => {
    try {
      setLoading(true)
      setError(null)
      const res = await api.get<{
        success: boolean
        data: { tickets: Ticket[]; pagination: { page: number; limit: number; total: number; totalPages: number } }
      }>('/api/tickets', {
        status: statusFilter !== 'all' ? statusFilter : undefined,
        priority: priorityFilter !== 'all' ? priorityFilter : undefined,
        page,
        limit: 15,
      })

      if (res.success && res.data) {
        setTickets(res.data.tickets)
        setTotalPages(res.data.pagination.totalPages)
      } else {
        setError(res.error || 'Failed to load tickets')
      }
    } catch {
      setError('Network error. Please try again.')
    } finally {
      setLoading(false)
    }
  }, [page, statusFilter, priorityFilter])

  const fetchSummary = useCallback(async () => {
    try {
      const res = await api.get<{ success: boolean; data: Ticket[] }>('/api/tickets', { limit: 1000 })
      if (res.success && res.data) {
        const all = res.data
        const open = all.filter((t) => t.status === 'OPEN').length
        const inProgress = all.filter((t) => t.status === 'IN_PROGRESS').length
        const resolved = all.filter((t) => t.status === 'RESOLVED').length
        // Average resolution time calculation (simplified)
        const resolvedTickets = all.filter((t) => t.status === 'RESOLVED' || t.status === 'CLOSED')
        let avgHours = 0
        if (resolvedTickets.length > 0) {
          const totalHours = resolvedTickets.reduce((sum, t) => {
            const created = new Date(t.createdAt).getTime()
            const updated = new Date(t.updatedAt).getTime()
            return sum + (updated - created) / (1000 * 60 * 60)
          }, 0)
          avgHours = totalHours / resolvedTickets.length
        }
        const avgStr = avgHours >= 24
          ? `${(avgHours / 24).toFixed(1)} days`
          : `${Math.round(avgHours)} hrs`

        setSummary({ open, inProgress, resolved, avgResolutionTime: avgStr })
      }
    } catch {
      // silent
    }
  }, [])

  useEffect(() => {
    fetchTickets()
  }, [fetchTickets])

  useEffect(() => {
    fetchSummary()
  }, [fetchSummary])

  const handleViewTicket = async (ticket: Ticket) => {
    try {
      setDetailLoading(true)
      setSelectedTicket(null)
      setDetailOpen(true)
      const res = await api.get<{
        success: boolean
        data: Ticket & { replies: TicketReply[] }
      }>(`/api/tickets/${ticket.id}`)
      if (res.success && res.data) {
        setSelectedTicket(res.data)
      } else {
        setSelectedTicket({ ...ticket, replies: [] })
      }
    } catch {
      setSelectedTicket({ ...ticket, replies: [] })
    } finally {
      setDetailLoading(false)
    }
  }

  const handleReply = async () => {
    if (!selectedTicket || !replyMessage.trim()) return
    try {
      setReplying(true)
      const res = await api.post<{ success: boolean; data: TicketReply; message?: string }>(
        `/api/tickets/${selectedTicket.id}`,
        { userId: selectedTicket.userId, message: replyMessage.trim(), isAdmin: true }
      )
      if (res.success) {
        toast({ title: 'Reply Sent', description: 'Your reply has been posted successfully.' })
        setReplyMessage('')
        // Refresh detail
        const detailRes = await api.get<{
          success: boolean
          data: Ticket & { replies: TicketReply[] }
        }>(`/api/tickets/${selectedTicket.id}`)
        if (detailRes.success && detailRes.data) {
          setSelectedTicket(detailRes.data)
        }
        fetchTickets()
        fetchSummary()
      } else {
        toast({ title: 'Error', description: res.error || 'Failed to send reply', variant: 'destructive' })
      }
    } catch {
      toast({ title: 'Error', description: 'Failed to send reply', variant: 'destructive' })
    } finally {
      setReplying(false)
    }
  }

  const handleUpdateStatus = async (ticketId: string, newStatus: string) => {
    try {
      setUpdatingStatus(true)
      const res = await api.put<{ success: boolean; message?: string }>(`/api/tickets/${ticketId}`, {
        status: newStatus,
      })
      if (res.success) {
        toast({ title: 'Status Updated', description: `Ticket status changed to ${statusLabels[newStatus] || newStatus}.` })
        // Refresh detail
        if (selectedTicket?.id === ticketId) {
          const detailRes = await api.get<{
            success: boolean
            data: Ticket & { replies: TicketReply[] }
          }>(`/api/tickets/${ticketId}`)
          if (detailRes.success && detailRes.data) {
            setSelectedTicket(detailRes.data)
          }
        }
        fetchTickets()
        fetchSummary()
      } else {
        toast({ title: 'Error', description: res.error || 'Failed to update status', variant: 'destructive' })
      }
    } catch {
      toast({ title: 'Error', description: 'Failed to update status', variant: 'destructive' })
    } finally {
      setUpdatingStatus(false)
    }
  }

  const filteredTickets = searchQuery
    ? tickets.filter(
        (t) =>
          t.subject.toLowerCase().includes(searchQuery.toLowerCase()) ||
          t.user?.name.toLowerCase().includes(searchQuery.toLowerCase()) ||
          t.id.toLowerCase().includes(searchQuery.toLowerCase()) ||
          t.description.toLowerCase().includes(searchQuery.toLowerCase())
      )
    : tickets

  return (
    <div className="space-y-6 p-4 md:p-6">
      {/* Header */}
      <div className="flex flex-col gap-4 sm:flex-row sm:items-center sm:justify-between">
        <div>
          <h1 className="text-2xl font-bold tracking-tight md:text-3xl">Support Tickets</h1>
          <p className="text-muted-foreground text-sm mt-1">
            Manage and respond to customer support requests
          </p>
        </div>
        <Button variant="outline" size="sm" onClick={() => { fetchTickets(); fetchSummary() }}>
          <RefreshCcw className="size-4" />
          <span className="hidden sm:inline">Refresh</span>
        </Button>
      </div>

      {/* Summary Cards */}
      {loading && !summary ? (
        <div className="grid gap-4 sm:grid-cols-2 lg:grid-cols-4">
          {[...Array(4)].map((_, i) => (
            <Card key={i} className="gap-4">
              <CardHeader className="flex flex-row items-center justify-between pb-0">
                <Skeleton className="h-4 w-24" />
                <Skeleton className="size-8 rounded-full" />
              </CardHeader>
              <CardContent>
                <Skeleton className="h-8 w-16" />
              </CardContent>
            </Card>
          ))}
        </div>
      ) : summary ? (
        <div className="grid gap-4 sm:grid-cols-2 lg:grid-cols-4">
          <Card className="gap-4">
            <CardHeader className="flex flex-row items-center justify-between pb-0">
              <CardTitle className="text-sm font-medium text-muted-foreground">Open Tickets</CardTitle>
              <div className="bg-blue-100 dark:bg-blue-900/30 rounded-full p-2">
                <AlertCircle className="size-4 text-blue-600 dark:text-blue-400" />
              </div>
            </CardHeader>
            <CardContent>
              <div className="text-2xl font-bold">{summary.open}</div>
              <p className="text-xs text-muted-foreground mt-1">Awaiting response</p>
            </CardContent>
          </Card>

          <Card className="gap-4">
            <CardHeader className="flex flex-row items-center justify-between pb-0">
              <CardTitle className="text-sm font-medium text-muted-foreground">In Progress</CardTitle>
              <div className="bg-amber-100 dark:bg-amber-900/30 rounded-full p-2">
                <Clock className="size-4 text-amber-600 dark:text-amber-400" />
              </div>
            </CardHeader>
            <CardContent>
              <div className="text-2xl font-bold">{summary.inProgress}</div>
              <p className="text-xs text-muted-foreground mt-1">Being worked on</p>
            </CardContent>
          </Card>

          <Card className="gap-4">
            <CardHeader className="flex flex-row items-center justify-between pb-0">
              <CardTitle className="text-sm font-medium text-muted-foreground">Resolved</CardTitle>
              <div className="bg-emerald-100 dark:bg-emerald-900/30 rounded-full p-2">
                <CheckCircle2 className="size-4 text-emerald-600 dark:text-emerald-400" />
              </div>
            </CardHeader>
            <CardContent>
              <div className="text-2xl font-bold">{summary.resolved}</div>
              <p className="text-xs text-muted-foreground mt-1">Successfully closed</p>
            </CardContent>
          </Card>

          <Card className="gap-4">
            <CardHeader className="flex flex-row items-center justify-between pb-0">
              <CardTitle className="text-sm font-medium text-muted-foreground">Avg. Resolution</CardTitle>
              <div className="bg-purple-100 dark:bg-purple-900/30 rounded-full p-2">
                <Timer className="size-4 text-purple-600 dark:text-purple-400" />
              </div>
            </CardHeader>
            <CardContent>
              <div className="text-2xl font-bold">{summary.avgResolutionTime}</div>
              <p className="text-xs text-muted-foreground mt-1">Average time to resolve</p>
            </CardContent>
          </Card>
        </div>
      ) : null}

      {/* Filter Bar */}
      <Card>
        <CardContent className="p-4">
          <div className="flex flex-col gap-3 sm:flex-row sm:items-end sm:flex-wrap">
            <div className="flex-1 min-w-[200px]">
              <Label className="text-xs mb-1.5 block">Search</Label>
              <div className="relative">
                <Search className="absolute left-2.5 top-2.5 size-4 text-muted-foreground" />
                <Input
                  placeholder="Ticket ID, subject, client..."
                  className="pl-9"
                  value={searchQuery}
                  onChange={(e) => setSearchQuery(e.target.value)}
                />
              </div>
            </div>

            <div className="w-full sm:w-[160px]">
              <Label className="text-xs mb-1.5 block">Status</Label>
              <Select value={statusFilter} onValueChange={(v) => { setStatusFilter(v); setPage(1) }}>
                <SelectTrigger className="w-full">
                  <SelectValue placeholder="All Status" />
                </SelectTrigger>
                <SelectContent>
                  <SelectItem value="all">All Status</SelectItem>
                  <SelectItem value="OPEN">Open</SelectItem>
                  <SelectItem value="IN_PROGRESS">In Progress</SelectItem>
                  <SelectItem value="RESOLVED">Resolved</SelectItem>
                  <SelectItem value="CLOSED">Closed</SelectItem>
                </SelectContent>
              </Select>
            </div>

            <div className="w-full sm:w-[160px]">
              <Label className="text-xs mb-1.5 block">Priority</Label>
              <Select value={priorityFilter} onValueChange={(v) => { setPriorityFilter(v); setPage(1) }}>
                <SelectTrigger className="w-full">
                  <SelectValue placeholder="All Priority" />
                </SelectTrigger>
                <SelectContent>
                  <SelectItem value="all">All Priority</SelectItem>
                  <SelectItem value="LOW">Low</SelectItem>
                  <SelectItem value="MEDIUM">Medium</SelectItem>
                  <SelectItem value="HIGH">High</SelectItem>
                  <SelectItem value="URGENT">Urgent</SelectItem>
                </SelectContent>
              </Select>
            </div>
          </div>
        </CardContent>
      </Card>

      {/* Tickets Table */}
      <Card>
        <CardContent className="p-0">
          {error ? (
            <div className="flex flex-col items-center justify-center py-16 text-muted-foreground">
              <XCircle className="size-10 mb-2 opacity-40" />
              <p className="font-medium">{error}</p>
              <Button variant="outline" size="sm" className="mt-3" onClick={fetchTickets}>
                <RefreshCcw className="size-4" />
                Retry
              </Button>
            </div>
          ) : (
            <div className="overflow-x-auto">
              <Table>
                <TableHeader>
                  <TableRow>
                    <TableHead className="w-[100px]">ID</TableHead>
                    <TableHead>Subject</TableHead>
                    <TableHead>Client</TableHead>
                    <TableHead>Priority</TableHead>
                    <TableHead>Status</TableHead>
                    <TableHead className="hidden md:table-cell">Assigned To</TableHead>
                    <TableHead className="hidden sm:table-cell">Created</TableHead>
                    <TableHead className="text-right">Actions</TableHead>
                  </TableRow>
                </TableHeader>
                <TableBody>
                  {loading ? (
                    [...Array(6)].map((_, i) => (
                      <TableRow key={i}>
                        {[...Array(8)].map((_, j) => (
                          <TableCell key={j}>
                            <Skeleton className="h-4 w-full" />
                          </TableCell>
                        ))}
                      </TableRow>
                    ))
                  ) : filteredTickets.length === 0 ? (
                    <TableRow>
                      <TableCell colSpan={8} className="text-center py-12 text-muted-foreground">
                        <MessageSquare className="size-10 mx-auto mb-2 opacity-40" />
                        <p>No tickets found</p>
                      </TableCell>
                    </TableRow>
                  ) : (
                    filteredTickets.map((ticket) => (
                      <TableRow key={ticket.id}>
                        <TableCell className="font-mono text-xs">
                          {ticket.id.slice(0, 8)}
                        </TableCell>
                        <TableCell>
                          <div className="max-w-[250px] truncate font-medium">
                            {ticket.subject}
                          </div>
                        </TableCell>
                        <TableCell>
                          <div>
                            <div className="font-medium text-sm">{ticket.user?.name || 'Unknown'}</div>
                            <div className="text-xs text-muted-foreground">{ticket.user?.email}</div>
                          </div>
                        </TableCell>
                        <TableCell>
                          <Badge
                            variant="secondary"
                            className={priorityBadgeColors[ticket.priority] || ''}
                          >
                            {ticket.priority}
                          </Badge>
                        </TableCell>
                        <TableCell>
                          <Badge
                            variant="secondary"
                            className={statusBadgeColors[ticket.status] || ''}
                          >
                            <span className={`mr-1 inline-block size-1.5 rounded-full ${statusDotColors[ticket.status] || ''}`} />
                            {statusLabels[ticket.status] || ticket.status}
                          </Badge>
                        </TableCell>
                        <TableCell className="hidden md:table-cell text-sm text-muted-foreground">
                          {ticket.assignedTo || <span className="text-muted-foreground/50">Unassigned</span>}
                        </TableCell>
                        <TableCell className="hidden sm:table-cell text-sm">
                          {formatDate(ticket.createdAt)}
                        </TableCell>
                        <TableCell className="text-right">
                          <Button
                            variant="ghost"
                            size="sm"
                            onClick={() => handleViewTicket(ticket)}
                          >
                            <Eye className="size-4" />
                          </Button>
                        </TableCell>
                      </TableRow>
                    ))
                  )}
                </TableBody>
              </Table>
            </div>
          )}
        </CardContent>

        {/* Pagination */}
        {totalPages > 1 && (
          <div className="flex items-center justify-between border-t px-4 py-3">
            <p className="text-sm text-muted-foreground">
              Page {page} of {totalPages}
            </p>
            <div className="flex gap-1">
              <Button
                variant="outline"
                size="sm"
                onClick={() => setPage((p) => Math.max(1, p - 1))}
                disabled={page === 1}
              >
                <ChevronLeft className="size-4" />
                Previous
              </Button>
              <Button
                variant="outline"
                size="sm"
                onClick={() => setPage((p) => Math.min(totalPages, p + 1))}
                disabled={page === totalPages}
              >
                Next
                <ChevronRight className="size-4" />
              </Button>
            </div>
          </div>
        )}
      </Card>

      {/* Ticket Detail Dialog */}
      <Dialog open={detailOpen} onOpenChange={setDetailOpen}>
        <DialogContent className="sm:max-w-2xl max-h-[90vh] overflow-hidden flex flex-col">
          <DialogHeader>
            <DialogTitle className="flex items-center gap-2">
              <Ticket className="size-5" />
              Ticket Details
            </DialogTitle>
            <DialogDescription>
              {selectedTicket ? `#${selectedTicket.id.slice(0, 8)}` : 'Loading...'}
            </DialogDescription>
          </DialogHeader>

          {detailLoading && !selectedTicket ? (
            <div className="flex-1 space-y-4 p-4">
              <Skeleton className="h-6 w-3/4" />
              <Skeleton className="h-4 w-1/2" />
              <Skeleton className="h-20 w-full" />
              <Skeleton className="h-20 w-full" />
              <Skeleton className="h-20 w-full" />
            </div>
          ) : selectedTicket ? (
            <div className="flex-1 overflow-hidden flex flex-col">
              <ScrollArea className="flex-1 px-1">
                <div className="space-y-5 pb-4">
                  {/* Status, Priority & Actions */}
                  <div className="flex flex-wrap items-center gap-2">
                    <Badge
                      variant="secondary"
                      className={statusBadgeColors[selectedTicket.status] || ''}
                    >
                      <span className={`mr-1 inline-block size-1.5 rounded-full ${statusDotColors[selectedTicket.status] || ''}`} />
                      {statusLabels[selectedTicket.status] || selectedTicket.status}
                    </Badge>
                    <Badge
                      variant="secondary"
                      className={priorityBadgeColors[selectedTicket.priority] || ''}
                    >
                      {selectedTicket.priority}
                    </Badge>
                    <span className="text-sm text-muted-foreground ml-auto">
                      Created {formatDate(selectedTicket.createdAt)}
                    </span>
                  </div>

                  {/* Status Change Actions */}
                  <div className="flex flex-wrap gap-2">
                    {selectedTicket.status !== 'IN_PROGRESS' && selectedTicket.status !== 'RESOLVED' && selectedTicket.status !== 'CLOSED' && (
                      <Button
                        variant="outline"
                        size="sm"
                        onClick={() => handleUpdateStatus(selectedTicket.id, 'IN_PROGRESS')}
                        disabled={updatingStatus}
                      >
                        {updatingStatus ? <Loader2 className="size-4 animate-spin" /> : <Clock className="size-4" />}
                        Mark In Progress
                      </Button>
                    )}
                    {selectedTicket.status !== 'RESOLVED' && selectedTicket.status !== 'CLOSED' && (
                      <Button
                        variant="outline"
                        size="sm"
                        className="text-emerald-600 border-emerald-300 hover:bg-emerald-50 dark:text-emerald-400 dark:border-emerald-800 dark:hover:bg-emerald-950"
                        onClick={() => handleUpdateStatus(selectedTicket.id, 'RESOLVED')}
                        disabled={updatingStatus}
                      >
                        {updatingStatus ? <Loader2 className="size-4 animate-spin" /> : <CheckCircle2 className="size-4" />}
                        Mark Resolved
                      </Button>
                    )}
                    {selectedTicket.status !== 'CLOSED' && (
                      <Button
                        variant="outline"
                        size="sm"
                        className="text-gray-600 border-gray-300 hover:bg-gray-50 dark:text-gray-400 dark:border-gray-700 dark:hover:bg-gray-900"
                        onClick={() => handleUpdateStatus(selectedTicket.id, 'CLOSED')}
                        disabled={updatingStatus}
                      >
                        {updatingStatus ? <Loader2 className="size-4 animate-spin" /> : <XCircle className="size-4" />}
                        Close Ticket
                      </Button>
                    )}
                  </div>

                  <Separator />

                  {/* Ticket Info */}
                  <div>
                    <h3 className="text-sm font-semibold mb-1">Subject</h3>
                    <p className="text-sm">{selectedTicket.subject}</p>
                  </div>

                  <div>
                    <h3 className="text-sm font-semibold mb-1">Description</h3>
                    <div className="rounded-lg bg-muted/50 p-3 text-sm whitespace-pre-wrap">
                      {selectedTicket.description}
                    </div>
                  </div>

                  <div className="grid grid-cols-2 gap-4 text-sm">
                    <div>
                      <span className="text-muted-foreground">Client</span>
                      <div className="font-medium mt-0.5">{selectedTicket.user?.name}</div>
                      <div className="text-xs text-muted-foreground">{selectedTicket.user?.email}</div>
                      {selectedTicket.user?.phone && (
                        <div className="text-xs text-muted-foreground">{selectedTicket.user.phone}</div>
                      )}
                    </div>
                    <div>
                      <span className="text-muted-foreground">Assigned To</span>
                      <div className="font-medium mt-0.5">{selectedTicket.assignedTo || 'Unassigned'}</div>
                      <div className="text-xs text-muted-foreground mt-0.5">
                        {selectedTicket._count?.replies || 0} replies
                      </div>
                    </div>
                  </div>

                  <Separator />

                  {/* Replies Thread */}
                  <div>
                    <h3 className="text-sm font-semibold mb-3 flex items-center gap-2">
                      <MessageSquare className="size-4" />
                      Replies ({selectedTicket.replies?.length || 0})
                    </h3>
                    <div className="space-y-3">
                      {selectedTicket.replies && selectedTicket.replies.length > 0 ? (
                        selectedTicket.replies.map((reply) => (
                          <div
                            key={reply.id}
                            className={`rounded-lg border p-3 text-sm ${
                              reply.isAdmin
                                ? 'bg-primary/5 border-primary/20 ml-0'
                                : 'bg-muted/30 mr-4 sm:mr-8'
                            }`}
                          >
                            <div className="flex items-center gap-2 mb-1.5">
                              <div className={`rounded-full p-1 ${reply.isAdmin ? 'bg-primary/10' : 'bg-muted'}`}>
                                <User className={`size-3 ${reply.isAdmin ? 'text-primary' : 'text-muted-foreground'}`} />
                              </div>
                              <span className="font-medium text-xs">
                                {reply.isAdmin ? 'Admin' : reply.user?.name || 'Client'}
                              </span>
                              <Badge
                                variant="secondary"
                                className={`text-[10px] px-1.5 py-0 ${reply.isAdmin ? 'bg-primary/10 text-primary' : 'bg-muted text-muted-foreground'}`}
                              >
                                {reply.isAdmin ? 'Staff' : 'Client'}
                              </Badge>
                              <span className="text-xs text-muted-foreground ml-auto">
                                {formatDateTime(reply.createdAt)}
                              </span>
                            </div>
                            <p className="whitespace-pre-wrap">{reply.message}</p>
                          </div>
                        ))
                      ) : (
                        <p className="text-sm text-muted-foreground text-center py-6">
                          No replies yet. Be the first to respond.
                        </p>
                      )}
                    </div>
                  </div>
                </div>
              </ScrollArea>

              {/* Reply Form */}
              {selectedTicket.status !== 'CLOSED' && (
                <>
                  <Separator />
                  <div className="pt-2">
                    <Label className="text-sm font-medium mb-1.5 block">Reply as Admin</Label>
                    <div className="flex gap-2">
                      <Textarea
                        placeholder="Type your reply here..."
                        value={replyMessage}
                        onChange={(e) => setReplyMessage(e.target.value)}
                        className="min-h-[60px] resize-none"
                        rows={2}
                        onKeyDown={(e) => {
                          if (e.key === 'Enter' && (e.metaKey || e.ctrlKey)) {
                            e.preventDefault()
                            handleReply()
                          }
                        }}
                      />
                      <Button
                        size="sm"
                        onClick={handleReply}
                        disabled={replying || !replyMessage.trim()}
                        className="self-end shrink-0"
                      >
                        {replying ? (
                          <Loader2 className="size-4 animate-spin" />
                        ) : (
                          <Send className="size-4" />
                        )}
                      </Button>
                    </div>
                    <p className="text-[10px] text-muted-foreground mt-1">
                      Press Ctrl+Enter to send
                    </p>
                  </div>
                </>
              )}
            </div>
          ) : null}
        </DialogContent>
      </Dialog>
    </div>
  )
}
