'use client'

import { useState, useEffect, useCallback } from 'react'
import {
  Search,
  Send,
  RefreshCw,
  MessageSquare,
  AlertTriangle,
  CheckCircle,
  XCircle,
  Clock,
  ChevronLeft,
  ChevronRight,
  ChevronsLeft,
  ChevronsRight,
  Phone,
  Eye,
  X,
  Loader2,
  Filter,
} from 'lucide-react'
import { Card, CardContent, CardHeader, CardTitle, CardDescription } from '@/components/ui/card'
import { Button } from '@/components/ui/button'
import { Badge } from '@/components/ui/badge'
import { Input } from '@/components/ui/input'
import { Skeleton } from '@/components/ui/skeleton'
import { Textarea } from '@/components/ui/textarea'
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from '@/components/ui/select'
import {
  Dialog,
  DialogContent,
  DialogHeader,
  DialogTitle,
  DialogDescription,
} from '@/components/ui/dialog'
import {
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableHeader,
  TableRow,
} from '@/components/ui/table'
import { api } from '@/lib/api'

// ---- Types ----
interface WhatsAppMessage {
  id: string
  phoneNumber: string
  message: string
  template: string
  status: 'SENT' | 'DELIVERED' | 'FAILED' | 'PENDING'
  response: string | null
  sentAt: string
}

// ---- Constants ----
const STATUS_OPTIONS = [
  { value: 'all', label: 'All Status' },
  { value: 'SENT', label: 'Sent' },
  { value: 'DELIVERED', label: 'Delivered' },
  { value: 'FAILED', label: 'Failed' },
  { value: 'PENDING', label: 'Pending' },
]

const statusBadgeColor: Record<string, string> = {
  SENT: 'bg-blue-100 text-blue-700 dark:bg-blue-900/30 dark:text-blue-400',
  DELIVERED: 'bg-emerald-100 text-emerald-700 dark:bg-emerald-900/30 dark:text-emerald-400',
  FAILED: 'bg-red-100 text-red-700 dark:bg-red-900/30 dark:text-red-400',
  PENDING: 'bg-amber-100 text-amber-700 dark:bg-amber-900/30 dark:text-amber-400',
}

const TEMPLATES = [
  'Payment Reminder',
  'Expiry Notice',
  'Welcome Message',
  'Invoice Generated',
  'Account Suspended',
  'Custom Message',
]

// ---- Skeleton Components ----
function SummaryCardSkeleton() {
  return (
    <Card className="p-4">
      <div className="flex items-center gap-4">
        <Skeleton className="size-10 rounded-lg" />
        <div className="flex-1 space-y-2">
          <Skeleton className="h-4 w-24" />
          <Skeleton className="h-7 w-16" />
        </div>
      </div>
    </Card>
  )
}

function TableSkeleton() {
  return (
    <div className="space-y-3">
      <Skeleton className="h-10 w-full" />
      {Array.from({ length: 8 }).map((_, i) => (
        <Skeleton key={i} className="h-12 w-full" />
      ))}
    </div>
  )
}

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

// ---- Pagination ----
function Pagination({
  page,
  totalPages,
  onPageChange,
}: {
  page: number
  totalPages: number
  onPageChange: (page: number) => void
}) {
  if (totalPages <= 1) return null

  return (
    <div className="flex items-center justify-between gap-4 pt-4">
      <p className="text-sm text-muted-foreground">
        Page {page} of {totalPages}
      </p>
      <div className="flex items-center gap-1">
        <Button
          variant="outline"
          size="icon"
          className="size-8"
          onClick={() => onPageChange(1)}
          disabled={page <= 1}
        >
          <ChevronsLeft className="size-4" />
        </Button>
        <Button
          variant="outline"
          size="icon"
          className="size-8"
          onClick={() => onPageChange(page - 1)}
          disabled={page <= 1}
        >
          <ChevronLeft className="size-4" />
        </Button>
        {Array.from({ length: Math.min(5, totalPages) }, (_, i) => {
          let pageNum: number
          if (totalPages <= 5) {
            pageNum = i + 1
          } else if (page <= 3) {
            pageNum = i + 1
          } else if (page >= totalPages - 2) {
            pageNum = totalPages - 4 + i
          } else {
            pageNum = page - 2 + i
          }
          return (
            <Button
              key={pageNum}
              variant={pageNum === page ? 'default' : 'outline'}
              size="icon"
              className="size-8"
              onClick={() => onPageChange(pageNum)}
            >
              {pageNum}
            </Button>
          )
        })}
        <Button
          variant="outline"
          size="icon"
          className="size-8"
          onClick={() => onPageChange(page + 1)}
          disabled={page >= totalPages}
        >
          <ChevronRight className="size-4" />
        </Button>
        <Button
          variant="outline"
          size="icon"
          className="size-8"
          onClick={() => onPageChange(totalPages)}
          disabled={page >= totalPages}
        >
          <ChevronsRight className="size-4" />
        </Button>
      </div>
    </div>
  )
}

// ---- Main Component ----
export default function WhatsAppView() {
  // Data state
  const [messages, setMessages] = useState<WhatsAppMessage[]>([])
  const [loading, setLoading] = useState(false)
  const [error, setError] = useState<string | null>(null)
  const [totalPages, setTotalPages] = useState(0)
  const [total, setTotal] = useState(0)

  // Summary counts
  const [summary, setSummary] = useState({
    totalSent: 0,
    delivered: 0,
    failed: 0,
    pending: 0,
  })
  const [summaryLoading, setSummaryLoading] = useState(true)

  // Filters
  const [statusFilter, setStatusFilter] = useState<string>('all')
  const [searchInput, setSearchInput] = useState('')
  const [searchQuery, setSearchQuery] = useState('')
  const [page, setPage] = useState(1)
  const [limit, setLimit] = useState(25)

  // Dialogs
  const [sendOpen, setSendOpen] = useState(false)
  const [detailOpen, setDetailOpen] = useState(false)
  const [selectedMessage, setSelectedMessage] = useState<WhatsAppMessage | null>(null)

  // Send form
  const [sendPhone, setSendPhone] = useState('')
  const [sendMessage, setSendMessage] = useState('')
  const [sendTemplate, setSendTemplate] = useState('')
  const [sending, setSending] = useState(false)
  const [sendError, setSendError] = useState<string | null>(null)

  // Search debounce
  useEffect(() => {
    const timeout = setTimeout(() => {
      setSearchQuery(searchInput)
    }, 400)
    return () => clearTimeout(timeout)
  }, [searchInput])

  // Reset page when filters change
  useEffect(() => {
    setPage(1)
  }, [statusFilter, searchQuery, limit])

  // Fetch messages
  const fetchMessages = useCallback(async () => {
    setLoading(true)
    setError(null)
    try {
      const params: Record<string, string | number> = {
        page,
        limit,
      }
      if (statusFilter && statusFilter !== 'all') params.status = statusFilter
      if (searchQuery) params.search = searchQuery

      const res = await api.get<{ data: WhatsAppMessage[] }>('/api/whatsapp', params)

      if (res.success && res.data) {
        const data = res.data.data || res.data
        if (Array.isArray(data)) {
          setMessages(data)
        } else {
          setMessages([])
        }
        if (res.pagination) {
          setTotalPages(res.pagination.totalPages)
          setTotal(res.pagination.total)
        } else {
          setTotalPages(1)
          setTotal(Array.isArray(data) ? data.length : 0)
        }
      } else {
        setError(res.error || 'Failed to load messages')
      }
    } catch (err: unknown) {
      const message = err instanceof Error ? err.message : 'Network error'
      setError(message)
    } finally {
      setLoading(false)
    }
  }, [statusFilter, searchQuery, page, limit])

  // Fetch summary
  const fetchSummary = useCallback(async () => {
    setSummaryLoading(true)
    try {
      const res = await api.get<{ data: WhatsAppMessage[] }>('/api/whatsapp', { limit: 200 })
      if (res.success && res.data) {
        const all = res.data.data || res.data
        if (Array.isArray(all)) {
          setSummary({
            totalSent: all.filter((m) => m.status === 'SENT').length,
            delivered: all.filter((m) => m.status === 'DELIVERED').length,
            failed: all.filter((m) => m.status === 'FAILED').length,
            pending: all.filter((m) => m.status === 'PENDING').length,
          })
        }
      }
    } catch {
      // Ignore
    } finally {
      setSummaryLoading(false)
    }
  }, [])

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

  // Send message handler
  const handleSendMessage = async () => {
    if (!sendPhone.trim() || !sendMessage.trim()) {
      setSendError('Phone number and message are required')
      return
    }
    setSending(true)
    setSendError(null)
    try {
      const res = await api.post('/api/whatsapp', {
        phoneNumber: sendPhone,
        message: sendMessage,
        template: sendTemplate,
      })
      if (res.success) {
        setSendOpen(false)
        setSendPhone('')
        setSendMessage('')
        setSendTemplate('')
        fetchMessages()
        fetchSummary()
      } else {
        setSendError(res.error || 'Failed to send message')
      }
    } catch {
      setSendError('Network error')
    } finally {
      setSending(false)
    }
  }

  return (
    <div className="space-y-6 p-4 md:p-6">
      {/* Header */}
      <div className="flex flex-col sm:flex-row sm:items-center sm:justify-between gap-4">
        <div>
          <h1 className="text-2xl md:text-3xl font-bold tracking-tight">WhatsApp Notifications</h1>
          <p className="text-muted-foreground mt-1">
            Manage WhatsApp messages and notification logs
          </p>
        </div>
        <div className="flex items-center gap-2">
          <Button variant="outline" size="sm" onClick={fetchMessages} disabled={loading}>
            <RefreshCw className={`size-4 ${loading ? 'animate-spin' : ''}`} />
            Refresh
          </Button>
          <Button size="sm" onClick={() => setSendOpen(true)}>
            <Send className="size-4" />
            Send Message
          </Button>
        </div>
      </div>

      {/* Summary Cards */}
      <div className="grid grid-cols-2 lg:grid-cols-4 gap-4">
        {summaryLoading ? (
          Array.from({ length: 4 }).map((_, i) => <SummaryCardSkeleton key={i} />)
        ) : (
          <>
            <Card className="p-4">
              <div className="flex items-center gap-3">
                <div className="flex items-center justify-center size-10 rounded-lg bg-blue-100 text-blue-600 dark:bg-blue-900/30 dark:text-blue-400">
                  <Send className="size-5" />
                </div>
                <div className="min-w-0">
                  <p className="text-xs text-muted-foreground font-medium">Total Sent</p>
                  <p className="text-lg font-bold truncate">{summary.totalSent}</p>
                </div>
              </div>
            </Card>
            <Card className="p-4">
              <div className="flex items-center gap-3">
                <div className="flex items-center justify-center size-10 rounded-lg bg-emerald-100 text-emerald-600 dark:bg-emerald-900/30 dark:text-emerald-400">
                  <CheckCircle className="size-5" />
                </div>
                <div className="min-w-0">
                  <p className="text-xs text-muted-foreground font-medium">Delivered</p>
                  <p className="text-lg font-bold truncate">{summary.delivered}</p>
                </div>
              </div>
            </Card>
            <Card className="p-4">
              <div className="flex items-center gap-3">
                <div className="flex items-center justify-center size-10 rounded-lg bg-red-100 text-red-600 dark:bg-red-900/30 dark:text-red-400">
                  <XCircle className="size-5" />
                </div>
                <div className="min-w-0">
                  <p className="text-xs text-muted-foreground font-medium">Failed</p>
                  <p className="text-lg font-bold truncate">{summary.failed}</p>
                </div>
              </div>
            </Card>
            <Card className="p-4">
              <div className="flex items-center gap-3">
                <div className="flex items-center justify-center size-10 rounded-lg bg-amber-100 text-amber-600 dark:bg-amber-900/30 dark:text-amber-400">
                  <Clock className="size-5" />
                </div>
                <div className="min-w-0">
                  <p className="text-xs text-muted-foreground font-medium">Pending</p>
                  <p className="text-lg font-bold truncate">{summary.pending}</p>
                </div>
              </div>
            </Card>
          </>
        )}
      </div>

      {/* Filter Bar */}
      <Card className="p-4">
        <div className="flex flex-col lg:flex-row gap-3">
          {/* Search */}
          <div className="relative flex-1">
            <Search className="absolute left-3 top-1/2 -translate-y-1/2 size-4 text-muted-foreground" />
            <Input
              placeholder="Search by phone number..."
              className="pl-9"
              value={searchInput}
              onChange={(e) => setSearchInput(e.target.value)}
            />
            {searchInput && (
              <Button
                variant="ghost"
                size="icon"
                className="absolute right-1 top-1/2 -translate-y-1/2 size-7"
                onClick={() => setSearchInput('')}
              >
                <X className="size-3" />
              </Button>
            )}
          </div>

          {/* Filters */}
          <div className="flex flex-wrap gap-2">
            <Select value={statusFilter} onValueChange={(v) => setStatusFilter(v)}>
              <SelectTrigger className="w-[140px]">
                <SelectValue placeholder="Status" />
              </SelectTrigger>
              <SelectContent>
                {STATUS_OPTIONS.map((opt) => (
                  <SelectItem key={opt.value} value={opt.value}>
                    {opt.label}
                  </SelectItem>
                ))}
              </SelectContent>
            </Select>

            <Select value={String(limit)} onValueChange={(v) => setLimit(Number(v))}>
              <SelectTrigger className="w-[80px]">
                <SelectValue />
              </SelectTrigger>
              <SelectContent>
                <SelectItem value="10">10</SelectItem>
                <SelectItem value="25">25</SelectItem>
                <SelectItem value="50">50</SelectItem>
                <SelectItem value="100">100</SelectItem>
              </SelectContent>
            </Select>
          </div>
        </div>
      </Card>

      {/* Data Table */}
      <Card>
        <CardContent className="p-0">
          {error ? (
            <div className="flex flex-col items-center justify-center py-16 gap-4">
              <AlertTriangle className="size-12 text-destructive" />
              <p className="text-muted-foreground text-center">{error}</p>
              <Button onClick={fetchMessages} variant="outline">
                Retry
              </Button>
            </div>
          ) : loading ? (
            <div className="p-4">
              <TableSkeleton />
            </div>
          ) : (
            <div>
              {/* Results count */}
              <div className="flex items-center justify-between px-4 py-3 border-b">
                <p className="text-sm text-muted-foreground">
                  Showing {messages.length} of {total} messages
                </p>
              </div>

              <div className="max-h-[500px] overflow-y-auto">
                <Table>
                  <TableHeader>
                    <TableRow>
                      <TableHead>Phone Number</TableHead>
                      <TableHead className="hidden md:table-cell">Message</TableHead>
                      <TableHead className="hidden sm:table-cell">Template</TableHead>
                      <TableHead>Status</TableHead>
                      <TableHead className="hidden lg:table-cell">Response</TableHead>
                      <TableHead className="hidden lg:table-cell">Sent At</TableHead>
                      <TableHead className="w-16">View</TableHead>
                    </TableRow>
                  </TableHeader>
                  <TableBody>
                    {messages.length === 0 ? (
                      <TableRow>
                        <TableCell colSpan={7} className="h-32 text-center">
                          <div className="flex flex-col items-center gap-2">
                            <MessageSquare className="size-8 text-muted-foreground opacity-50" />
                            <p className="text-muted-foreground text-sm">No messages found</p>
                          </div>
                        </TableCell>
                      </TableRow>
                    ) : (
                      messages.map((msg) => (
                        <TableRow key={msg.id}>
                          <TableCell className="font-medium text-sm">
                            <div className="flex items-center gap-1.5">
                              <Phone className="size-3 text-muted-foreground" />
                              {msg.phoneNumber}
                            </div>
                          </TableCell>
                          <TableCell className="hidden md:table-cell text-xs text-muted-foreground max-w-[200px] truncate">
                            {msg.message || 'N/A'}
                          </TableCell>
                          <TableCell className="hidden sm:table-cell text-xs text-muted-foreground">
                            {msg.template || 'N/A'}
                          </TableCell>
                          <TableCell>
                            <Badge
                              variant="secondary"
                              className={statusBadgeColor[msg.status] || ''}
                            >
                              {msg.status}
                            </Badge>
                          </TableCell>
                          <TableCell className="hidden lg:table-cell text-xs text-muted-foreground max-w-[120px] truncate">
                            {msg.response || '—'}
                          </TableCell>
                          <TableCell className="hidden lg:table-cell text-xs text-muted-foreground">
                            {formatDateTime(msg.sentAt)}
                          </TableCell>
                          <TableCell>
                            <Button
                              variant="ghost"
                              size="icon"
                              className="size-8"
                              onClick={() => {
                                setSelectedMessage(msg)
                                setDetailOpen(true)
                              }}
                            >
                              <Eye className="size-3.5" />
                            </Button>
                          </TableCell>
                        </TableRow>
                      ))
                    )}
                  </TableBody>
                </Table>
              </div>

              <div className="px-4">
                <Pagination page={page} totalPages={totalPages} onPageChange={setPage} />
              </div>
            </div>
          )}
        </CardContent>
      </Card>

      {/* Send Message Dialog */}
      <Dialog open={sendOpen} onOpenChange={setSendOpen}>
        <DialogContent className="sm:max-w-md">
          <DialogHeader>
            <DialogTitle className="flex items-center gap-2">
              <Send className="size-5 text-emerald-500" />
              Send WhatsApp Message
            </DialogTitle>
            <DialogDescription>
              Send a WhatsApp message to a client
            </DialogDescription>
          </DialogHeader>
          <div className="space-y-4 pt-2">
            <div className="space-y-2">
              <label className="text-sm font-medium">Phone Number *</label>
              <Input
                placeholder="+880 1XXX XXXXXX"
                value={sendPhone}
                onChange={(e) => setSendPhone(e.target.value)}
              />
            </div>
            <div className="space-y-2">
              <label className="text-sm font-medium">Template</label>
              <Select value={sendTemplate} onValueChange={setSendTemplate}>
                <SelectTrigger>
                  <SelectValue placeholder="Select template" />
                </SelectTrigger>
                <SelectContent>
                  {TEMPLATES.map((t) => (
                    <SelectItem key={t} value={t}>
                      {t}
                    </SelectItem>
                  ))}
                </SelectContent>
              </Select>
            </div>
            <div className="space-y-2">
              <label className="text-sm font-medium">Message *</label>
              <Textarea
                placeholder="Enter your message..."
                value={sendMessage}
                onChange={(e) => setSendMessage(e.target.value)}
                rows={4}
              />
            </div>
            {sendError && (
              <p className="text-sm text-destructive">{sendError}</p>
            )}
            <div className="flex items-center justify-end gap-2 pt-2">
              <Button variant="outline" onClick={() => setSendOpen(false)}>
                Cancel
              </Button>
              <Button onClick={handleSendMessage} disabled={sending}>
                {sending ? (
                  <>
                    <Loader2 className="size-4 animate-spin" />
                    Sending...
                  </>
                ) : (
                  <>
                    <Send className="size-4" />
                    Send
                  </>
                )}
              </Button>
            </div>
          </div>
        </DialogContent>
      </Dialog>

      {/* Message Detail Dialog */}
      <Dialog open={detailOpen} onOpenChange={setDetailOpen}>
        <DialogContent className="sm:max-w-lg">
          <DialogHeader>
            <DialogTitle className="flex items-center gap-2">
              <MessageSquare className="size-5" />
              Message Details
            </DialogTitle>
          </DialogHeader>
          {selectedMessage && (
            <div className="space-y-4 pt-2">
              <div className="grid grid-cols-2 gap-4">
                <div>
                  <p className="text-xs text-muted-foreground">Phone Number</p>
                  <p className="text-sm font-medium">{selectedMessage.phoneNumber}</p>
                </div>
                <div>
                  <p className="text-xs text-muted-foreground">Status</p>
                  <Badge
                    variant="secondary"
                    className={statusBadgeColor[selectedMessage.status] || ''}
                  >
                    {selectedMessage.status}
                  </Badge>
                </div>
                <div>
                  <p className="text-xs text-muted-foreground">Template</p>
                  <p className="text-sm font-medium">{selectedMessage.template || 'N/A'}</p>
                </div>
                <div>
                  <p className="text-xs text-muted-foreground">Sent At</p>
                  <p className="text-sm font-medium">{formatDateTime(selectedMessage.sentAt)}</p>
                </div>
              </div>
              <div>
                <p className="text-xs text-muted-foreground mb-1">Message</p>
                <div className="bg-muted rounded-lg p-3 text-sm whitespace-pre-wrap max-h-40 overflow-y-auto">
                  {selectedMessage.message}
                </div>
              </div>
              {selectedMessage.response && (
                <div>
                  <p className="text-xs text-muted-foreground mb-1">Response</p>
                  <div className="bg-muted rounded-lg p-3 text-sm whitespace-pre-wrap">
                    {selectedMessage.response}
                  </div>
                </div>
              )}
              <div className="flex justify-end">
                <Button variant="outline" onClick={() => setDetailOpen(false)}>
                  Close
                </Button>
              </div>
            </div>
          )}
        </DialogContent>
      </Dialog>
    </div>
  )
}
