'use client'

import { useState, useEffect, useCallback } from 'react'
import {
  MapPin,
  Plus,
  Search,
  Pencil,
  Trash2,
  RefreshCcw,
  Loader2,
  Users,
  LayoutGrid,
  CheckCircle,
  ChevronLeft,
  ChevronRight,
  ChevronsLeft,
  ChevronsRight,
  X,
  AlertTriangle,
} from 'lucide-react'
import { Card, CardContent } 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 { Skeleton } from '@/components/ui/skeleton'
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from '@/components/ui/select'
import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogFooter,
  DialogHeader,
  DialogTitle,
} from '@/components/ui/dialog'
import {
  AlertDialog,
  AlertDialogAction,
  AlertDialogCancel,
  AlertDialogContent,
  AlertDialogDescription,
  AlertDialogFooter,
  AlertDialogHeader,
  AlertDialogTitle,
} from '@/components/ui/alert-dialog'
import {
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableHeader,
  TableRow,
} from '@/components/ui/table'
import { useToast } from '@/hooks/use-toast'
import { api } from '@/lib/api'

// ---- Types ----
interface Area {
  id: string
  name: string
  code: string
  description: string
  createdAt: string
  updatedAt: string
  _count: {
    users: number
    plans: number
  }
}

interface AreasResponse {
  areas: Area[]
  pagination: {
    page: number
    limit: number
    total: number
    totalPages: number
  }
}

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

// ---- Summary Card ----
function SummaryCard({
  title,
  value,
  icon: Icon,
  color,
}: {
  title: string
  value: number | string
  icon: React.ElementType
  color: string
}) {
  return (
    <Card className="gap-0">
      <CardContent className="p-4 md:p-6">
        <div className="flex items-center gap-4">
          <div className={`flex items-center justify-center size-10 md:size-12 rounded-xl ${color}`}>
            <Icon className="size-5 md:size-6 text-white" />
          </div>
          <div>
            <p className="text-sm text-muted-foreground">{title}</p>
            <p className="text-2xl md:text-3xl font-bold tracking-tight">{value}</p>
          </div>
        </div>
      </CardContent>
    </Card>
  )
}

// ---- Pagination Component ----
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>
  )
}

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

// ---- Default form ----
const defaultForm = {
  name: '',
  code: '',
  description: '',
}

// ---- Main Component ----
export default function AreasView() {
  const { toast } = useToast()

  // Data state
  const [areas, setAreas] = useState<Area[]>([])
  const [total, setTotal] = useState(0)
  const [totalPages, setTotalPages] = useState(0)
  const [loading, setLoading] = useState(true)
  const [error, setError] = useState<string | null>(null)

  // Summary stats
  const [stats, setStats] = useState({
    totalAreas: 0,
    totalClients: 0,
    areasWithPlans: 0,
    activePlans: 0,
  })

  // Filter state
  const [searchQuery, setSearchQuery] = useState('')
  const [searchInput, setSearchInput] = useState('')
  const [page, setPage] = useState(1)
  const [perPage, setPerPage] = useState(20)

  // Add/Edit dialog
  const [formOpen, setFormOpen] = useState(false)
  const [editingArea, setEditingArea] = useState<Area | null>(null)
  const [form, setForm] = useState(defaultForm)
  const [submitting, setSubmitting] = useState(false)

  // Delete dialog
  const [deleteTarget, setDeleteTarget] = useState<Area | null>(null)
  const [deleting, setDeleting] = useState(false)

  // Fetch areas
  const fetchAreas = useCallback(async () => {
    setLoading(true)
    setError(null)
    try {
      const res = await api.get<{ data: AreasResponse }>('/api/areas', {
        search: searchQuery || undefined,
        limit: perPage,
        page,
      })

      if (res.success && res.data) {
        setAreas(res.data.data.areas)
        setTotal(res.data.data.pagination.total)
        setTotalPages(res.data.data.pagination.totalPages)

        // Compute summary stats
        const allAreas = res.data.data.areas
        const totalClients = allAreas.reduce((sum, a) => sum + a._count.users, 0)
        const areasWithPlans = allAreas.filter((a) => a._count.plans > 0).length
        const activePlans = allAreas.reduce((sum, a) => sum + a._count.plans, 0)

        // If we're on page 1 with enough items, use these for stats
        // Otherwise fetch all for accurate summary
        if (page === 1 && res.data.data.pagination.total <= perPage) {
          setStats({
            totalAreas: res.data.data.pagination.total,
            totalClients,
            areasWithPlans,
            activePlans,
          })
        } else {
          // Fetch summary separately
          const summaryRes = await api.get<{ data: AreasResponse }>('/api/areas', {
            limit: 500,
          })
          if (summaryRes.success && summaryRes.data) {
            const all = summaryRes.data.data.areas
            setStats({
              totalAreas: summaryRes.data.data.pagination.total,
              totalClients: all.reduce((s, a) => s + a._count.users, 0),
              areasWithPlans: all.filter((a) => a._count.plans > 0).length,
              activePlans: all.reduce((s, a) => s + a._count.plans, 0),
            })
          }
        }
      } else {
        setError(res.error || 'Failed to load areas')
      }
    } catch {
      setError('Network error. Please try again.')
    } finally {
      setLoading(false)
    }
  }, [searchQuery, page, perPage])

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

  // Reset page on filter change
  useEffect(() => {
    setPage(1)
  }, [searchQuery, perPage])

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

  // Handlers
  const handleOpenAdd = () => {
    setEditingArea(null)
    setForm(defaultForm)
    setFormOpen(true)
  }

  const handleOpenEdit = (area: Area) => {
    setEditingArea(area)
    setForm({
      name: area.name,
      code: area.code,
      description: area.description,
    })
    setFormOpen(true)
  }

  const handleSubmit = async () => {
    if (!form.name.trim() || !form.code.trim()) {
      toast({
        title: 'Validation Error',
        description: 'Name and code are required',
        variant: 'destructive',
      })
      return
    }

    try {
      setSubmitting(true)
      if (editingArea) {
        const res = await api.put(`/api/areas/${editingArea.id}`, {
          name: form.name,
          code: form.code,
          description: form.description,
        })
        if (res.success) {
          toast({ title: 'Success', description: 'Area updated successfully' })
          setFormOpen(false)
          fetchAreas()
        } else {
          toast({ title: 'Error', description: res.error || 'Failed to update area', variant: 'destructive' })
        }
      } else {
        const res = await api.post('/api/areas', {
          name: form.name,
          code: form.code,
          description: form.description,
        })
        if (res.success) {
          toast({ title: 'Success', description: 'Area created successfully' })
          setFormOpen(false)
          fetchAreas()
        } else {
          toast({ title: 'Error', description: res.error || 'Failed to create area', variant: 'destructive' })
        }
      }
    } catch {
      toast({ title: 'Error', description: 'Network error', variant: 'destructive' })
    } finally {
      setSubmitting(false)
    }
  }

  const handleDelete = async () => {
    if (!deleteTarget) return
    try {
      setDeleting(true)
      const res = await api.del(`/api/areas/${deleteTarget.id}`)
      if (res.success) {
        toast({ title: 'Success', description: 'Area deleted successfully' })
        setDeleteTarget(null)
        fetchAreas()
      } else {
        toast({ title: 'Error', description: res.error || 'Failed to delete area', variant: 'destructive' })
      }
    } catch {
      toast({ title: 'Error', description: 'Network error', variant: 'destructive' })
    } finally {
      setDeleting(false)
    }
  }

  return (
    <div className="space-y-4 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">Area Management</h1>
          <p className="text-muted-foreground mt-1">
            Manage service areas, zones, and coverage regions
          </p>
        </div>
        <div className="flex items-center gap-2">
          <Button variant="outline" size="sm" onClick={fetchAreas}>
            <RefreshCcw className="size-4" />
            <span className="hidden sm:inline">Refresh</span>
          </Button>
          <Button size="sm" onClick={handleOpenAdd}>
            <Plus className="size-4" />
            Add Area
          </Button>
        </div>
      </div>

      {/* Summary Cards */}
      <div className="grid grid-cols-2 lg:grid-cols-4 gap-4">
        <SummaryCard
          title="Total Areas"
          value={stats.totalAreas}
          icon={MapPin}
          color="bg-emerald-600"
        />
        <SummaryCard
          title="Total Clients"
          value={stats.totalClients}
          icon={Users}
          color="bg-sky-600"
        />
        <SummaryCard
          title="Areas with Plans"
          value={stats.areasWithPlans}
          icon={LayoutGrid}
          color="bg-amber-600"
        />
        <SummaryCard
          title="Active Plans"
          value={stats.activePlans}
          icon={CheckCircle}
          color="bg-violet-600"
        />
      </div>

      {/* Search & Filter Bar */}
      <Card className="p-4">
        <div className="flex flex-col sm:flex-row gap-3">
          <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 name, code, or description..."
              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>
          <Select value={String(perPage)} onValueChange={(v) => setPerPage(Number(v))}>
            <SelectTrigger className="w-[100px]">
              <SelectValue />
            </SelectTrigger>
            <SelectContent>
              <SelectItem value="10">10</SelectItem>
              <SelectItem value="20">20</SelectItem>
              <SelectItem value="50">50</SelectItem>
            </SelectContent>
          </Select>
        </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={fetchAreas} variant="outline">
                Retry
              </Button>
            </div>
          ) : loading ? (
            <TableSkeleton />
          ) : (
            <div>
              {/* Results count */}
              <div className="flex items-center justify-between px-4 py-3 border-b">
                <p className="text-sm text-muted-foreground">
                  Showing {areas.length} of {total} areas
                </p>
              </div>

              <div className="overflow-x-auto">
                <Table>
                  <TableHeader>
                    <TableRow>
                      <TableHead>Name</TableHead>
                      <TableHead>Code</TableHead>
                      <TableHead className="hidden md:table-cell">Description</TableHead>
                      <TableHead className="text-center">Users</TableHead>
                      <TableHead className="text-center hidden sm:table-cell">Plans</TableHead>
                      <TableHead className="hidden lg:table-cell">Created Date</TableHead>
                      <TableHead className="w-24 text-right">Actions</TableHead>
                    </TableRow>
                  </TableHeader>
                  <TableBody>
                    {areas.length === 0 ? (
                      <TableRow>
                        <TableCell colSpan={7} className="h-32 text-center">
                          <div className="flex flex-col items-center gap-2">
                            <MapPin className="size-8 text-muted-foreground opacity-50" />
                            <p className="text-muted-foreground text-sm">No areas found</p>
                          </div>
                        </TableCell>
                      </TableRow>
                    ) : (
                      areas.map((area) => (
                        <TableRow key={area.id}>
                          <TableCell>
                            <div className="flex items-center gap-2">
                              <div className="flex items-center justify-center size-8 rounded-lg bg-emerald-100 dark:bg-emerald-900/30">
                                <MapPin className="size-4 text-emerald-600 dark:text-emerald-400" />
                              </div>
                              <span className="font-medium">{area.name}</span>
                            </div>
                          </TableCell>
                          <TableCell>
                            <Badge variant="outline" className="font-mono text-xs">
                              {area.code}
                            </Badge>
                          </TableCell>
                          <TableCell className="hidden md:table-cell max-w-[200px]">
                            <span className="text-sm text-muted-foreground line-clamp-1">
                              {area.description || '—'}
                            </span>
                          </TableCell>
                          <TableCell className="text-center">
                            <Badge variant="secondary" className="bg-sky-100 text-sky-700 dark:bg-sky-900/30 dark:text-sky-400">
                              {area._count.users}
                            </Badge>
                          </TableCell>
                          <TableCell className="text-center hidden sm:table-cell">
                            <Badge variant="secondary" className="bg-amber-100 text-amber-700 dark:bg-amber-900/30 dark:text-amber-400">
                              {area._count.plans}
                            </Badge>
                          </TableCell>
                          <TableCell className="hidden lg:table-cell text-sm text-muted-foreground">
                            {formatDate(area.createdAt)}
                          </TableCell>
                          <TableCell className="text-right">
                            <div className="flex items-center justify-end gap-1">
                              <Button variant="ghost" size="icon" className="size-8" onClick={() => handleOpenEdit(area)}>
                                <Pencil className="size-4" />
                              </Button>
                              <Button
                                variant="ghost"
                                size="icon"
                                className="size-8 text-red-600 hover:text-red-700 hover:bg-red-50 dark:hover:bg-red-900/20"
                                onClick={() => setDeleteTarget(area)}
                              >
                                <Trash2 className="size-4" />
                              </Button>
                            </div>
                          </TableCell>
                        </TableRow>
                      ))
                    )}
                  </TableBody>
                </Table>
              </div>

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

      {/* Add/Edit Area Dialog */}
      <Dialog open={formOpen} onOpenChange={setFormOpen}>
        <DialogContent className="sm:max-w-lg">
          <DialogHeader>
            <DialogTitle className="flex items-center gap-2">
              {editingArea ? <Pencil className="size-5" /> : <Plus className="size-5" />}
              {editingArea ? 'Edit Area' : 'Add Area'}
            </DialogTitle>
            <DialogDescription>
              {editingArea ? 'Update area details' : 'Create a new service area or zone'}
            </DialogDescription>
          </DialogHeader>
          <div className="space-y-4">
            <div>
              <Label>Area Name *</Label>
              <Input
                className="mt-1.5"
                placeholder="e.g., Dhanmondi Zone"
                value={form.name}
                onChange={(e) => setForm((prev) => ({ ...prev, name: e.target.value }))}
              />
            </div>
            <div>
              <Label>Area Code *</Label>
              <Input
                className="mt-1.5"
                placeholder="e.g., DM-01"
                value={form.code}
                onChange={(e) => setForm((prev) => ({ ...prev, code: e.target.value.toUpperCase() }))}
                disabled={!!editingArea}
              />
              {editingArea && (
                <p className="text-xs text-muted-foreground mt-1">Code cannot be changed after creation</p>
              )}
            </div>
            <div>
              <Label>Description</Label>
              <Textarea
                className="mt-1.5"
                placeholder="Brief description of the area..."
                value={form.description}
                onChange={(e) => setForm((prev) => ({ ...prev, description: e.target.value }))}
                rows={3}
              />
            </div>
          </div>
          <DialogFooter>
            <Button variant="outline" onClick={() => setFormOpen(false)}>
              Cancel
            </Button>
            <Button onClick={handleSubmit} disabled={submitting}>
              {submitting ? (
                <Loader2 className="size-4 animate-spin" />
              ) : editingArea ? (
                <Pencil className="size-4" />
              ) : (
                <Plus className="size-4" />
              )}
              {editingArea ? 'Update Area' : 'Create Area'}
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>

      {/* Delete Confirmation Dialog */}
      <AlertDialog open={!!deleteTarget} onOpenChange={() => setDeleteTarget(null)}>
        <AlertDialogContent>
          <AlertDialogHeader>
            <AlertDialogTitle>Delete Area</AlertDialogTitle>
            <AlertDialogDescription>
              Are you sure you want to delete &quot;{deleteTarget?.name}&quot;? This action cannot be
              undone. Areas with associated users or plans cannot be deleted.
            </AlertDialogDescription>
          </AlertDialogHeader>
          <AlertDialogFooter>
            <AlertDialogCancel>Cancel</AlertDialogCancel>
            <AlertDialogAction
              onClick={handleDelete}
              disabled={deleting}
              className="bg-red-600 hover:bg-red-700"
            >
              {deleting ? <Loader2 className="size-4 animate-spin" /> : <Trash2 className="size-4" />}
              Delete
            </AlertDialogAction>
          </AlertDialogFooter>
        </AlertDialogContent>
      </AlertDialog>
    </div>
  )
}
