'use client'

import { useState, useEffect, useCallback, useMemo } from 'react'
import {
  Plus,
  Search,
  Pencil,
  Trash2,
  RefreshCcw,
  Loader2,
  Zap,
  Users,
  ArrowDown,
  ArrowUp,
  Gauge,
  Package,
} from 'lucide-react'
import { Card, CardContent, CardDescription, 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 { Switch } from '@/components/ui/switch'
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 { Skeleton } from '@/components/ui/skeleton'
import {
  ChartContainer,
  ChartTooltip,
  ChartTooltipContent,
  type ChartConfig,
} from '@/components/ui/chart'
import { useToast } from '@/hooks/use-toast'
import { api } from '@/lib/api'
import { Bar, BarChart, XAxis, YAxis } from 'recharts'

interface Plan {
  id: string
  name: string
  description: string
  speedDown: number
  speedUp: number
  price: number
  duration: number
  isActive: boolean
  areaId: string | null
  area: { id: string; name: string } | null
  _count: { subscriptions: number }
}

const chartConfig: ChartConfig = {
  speedDown: {
    label: 'Download (Mbps)',
    color: 'var(--chart-1, #10b981)',
  },
  speedUp: {
    label: 'Upload (Mbps)',
    color: 'var(--chart-2, #0ea5e9)',
  },
}

function formatCurrency(amount: number): string {
  return new Intl.NumberFormat('en-BD', {
    style: 'currency',
    currency: 'BDT',
    minimumFractionDigits: 0,
  }).format(amount)
}

const defaultForm = {
  name: '',
  description: '',
  speedDown: '10',
  speedUp: '5',
  price: '',
  duration: '30',
  areaId: '',
  isActive: true,
}

export default function PlansView() {
  const { toast } = useToast()
  const [plans, setPlans] = useState<Plan[]>([])
  const [loading, setLoading] = useState(true)
  const [searchQuery, setSearchQuery] = useState('')
  const [areaFilter, setAreaFilter] = useState('')
  const [areas, setAreas] = useState<{ id: string; name: string }[]>([])

  // Dialog states
  const [formOpen, setFormOpen] = useState(false)
  const [editingPlan, setEditingPlan] = useState<Plan | null>(null)
  const [form, setForm] = useState(defaultForm)
  const [submitting, setSubmitting] = useState(false)

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

  const fetchPlans = useCallback(async () => {
    try {
      setLoading(true)
      const params = new URLSearchParams()
      params.set('limit', '50')
      if (searchQuery) params.set('search', searchQuery)
      if (areaFilter) params.set('areaId', areaFilter)

      const res = await api.get<{
        success: boolean
        data: { plans: Plan[] }
      }>(`/api/plans?${params.toString()}`)

      if (res.success) setPlans(res.data.plans)
    } catch {
      toast({ title: 'Error', description: 'Failed to load plans', variant: 'destructive' })
    } finally {
      setLoading(false)
    }
  }, [searchQuery, areaFilter, toast])

  const fetchAreas = useCallback(async () => {
    try {
      const res = await api.get<{ success: boolean; data: { areas: { id: string; name: string }[] } }>(
        '/api/areas?limit=50'
      )
      if (res.success) setAreas(res.data.areas)
    } catch {
      // silent
    }
  }, [])

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

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

  // Speed chart data
  const chartData = useMemo(
    () =>
      plans.map((plan) => ({
        name: plan.name.length > 12 ? plan.name.slice(0, 12) + '...' : plan.name,
        speedDown: plan.speedDown,
        speedUp: plan.speedUp,
      })),
    [plans]
  )

  const handleOpenAdd = () => {
    setEditingPlan(null)
    setForm(defaultForm)
    setFormOpen(true)
  }

  const handleOpenEdit = (plan: Plan) => {
    setEditingPlan(plan)
    setForm({
      name: plan.name,
      description: plan.description,
      speedDown: String(plan.speedDown),
      speedUp: String(plan.speedUp),
      price: String(plan.price),
      duration: String(plan.duration),
      areaId: plan.areaId || '',
      isActive: plan.isActive,
    })
    setFormOpen(true)
  }

  const handleSubmit = async () => {
    if (!form.name || !form.price) {
      toast({
        title: 'Validation Error',
        description: 'Name and price are required',
        variant: 'destructive',
      })
      return
    }
    try {
      setSubmitting(true)
      const body = {
        name: form.name,
        description: form.description,
        speedDown: parseInt(form.speedDown) || 10,
        speedUp: parseInt(form.speedUp) || 5,
        price: parseFloat(form.price),
        duration: parseInt(form.duration) || 30,
        areaId: form.areaId || null,
        isActive: form.isActive,
      }

      if (editingPlan) {
        const res = await api.put<{ success: boolean; message: string }>(
          `/api/plans/${editingPlan.id}`,
          body
        )
        if (res.success) {
          toast({ title: 'Success', description: 'Plan updated successfully' })
          setFormOpen(false)
          fetchPlans()
        }
      } else {
        const res = await api.post<{ success: boolean; message: string }>('/api/plans', body)
        if (res.success) {
          toast({ title: 'Success', description: 'Plan created successfully' })
          setFormOpen(false)
          fetchPlans()
        }
      }
    } catch (err) {
      toast({
        title: 'Error',
        description: err instanceof Error ? err.message : 'Failed to save plan',
        variant: 'destructive',
      })
    } finally {
      setSubmitting(false)
    }
  }

  const handleToggleActive = async (plan: Plan) => {
    try {
      const res = await api.put<{ success: boolean }>(`/api/plans/${plan.id}`, {
        isActive: !plan.isActive,
      })
      if (res.success) {
        toast({
          title: 'Updated',
          description: `${plan.name} is now ${plan.isActive ? 'inactive' : 'active'}`,
        })
        fetchPlans()
      }
    } catch {
      toast({ title: 'Error', description: 'Failed to update plan', variant: 'destructive' })
    }
  }

  const handleDelete = async () => {
    if (!deleteTarget) return
    try {
      setDeleting(true)
      const res = await api.delete<{ success: boolean; message: string }>(
        `/api/plans/${deleteTarget.id}`
      )
      if (res.success) {
        toast({ title: 'Success', description: res.message })
        setDeleteTarget(null)
        fetchPlans()
      }
    } catch (err) {
      toast({
        title: 'Error',
        description: err instanceof Error ? err.message : 'Failed to delete plan',
        variant: 'destructive',
      })
    } finally {
      setDeleting(false)
    }
  }

  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">Plans</h1>
          <p className="text-muted-foreground text-sm mt-1">
            Manage internet plans and pricing
          </p>
        </div>
        <div className="flex gap-2">
          <Button variant="outline" size="sm" onClick={fetchPlans}>
            <RefreshCcw className="size-4" />
            <span className="hidden sm:inline">Refresh</span>
          </Button>
          <Button size="sm" onClick={handleOpenAdd}>
            <Plus className="size-4" />
            Add Plan
          </Button>
        </div>
      </div>

      {/* Filter Bar */}
      <div className="flex flex-col gap-3 sm:flex-row sm:items-end">
        <div className="flex-1 min-w-[200px]">
          <Label className="text-xs mb-1.5 block">Search Plans</Label>
          <div className="relative">
            <Search className="absolute left-2.5 top-2.5 size-4 text-muted-foreground" />
            <Input
              placeholder="Search by name..."
              className="pl-9"
              value={searchQuery}
              onChange={(e) => setSearchQuery(e.target.value)}
            />
          </div>
        </div>
        <div className="w-full sm:w-[180px]">
          <Label className="text-xs mb-1.5 block">Filter by Area</Label>
          <Select value={areaFilter} onValueChange={(v) => setAreaFilter(v === '__all__' ? '' : v)}>
            <SelectTrigger className="w-full">
              <SelectValue placeholder="All Areas" />
            </SelectTrigger>
            <SelectContent>
              <SelectItem value="__all__">All Areas</SelectItem>
              {areas.map((area) => (
                <SelectItem key={area.id} value={area.id}>
                  {area.name}
                </SelectItem>
              ))}
            </SelectContent>
          </Select>
        </div>
      </div>

      {/* Speed Comparison Chart */}
      {plans.length > 0 && (
        <Card>
          <CardHeader>
            <CardTitle className="flex items-center gap-2">
              <Gauge className="size-5" />
              Speed Comparison
            </CardTitle>
            <CardDescription>Download and upload speeds across all plans</CardDescription>
          </CardHeader>
          <CardContent>
            <ChartContainer config={chartConfig} className="h-[250px] w-full">
              <BarChart data={chartData} layout="vertical" margin={{ top: 5, right: 20, left: 80, bottom: 5 }}>
                <XAxis type="number" tickLine={false} axisLine={false} unit=" Mbps" />
                <YAxis type="category" dataKey="name" tickLine={false} axisLine={false} width={80} />
                <ChartTooltip content={<ChartTooltipContent />} />
                <Bar dataKey="speedDown" fill="var(--color-speedDown)" radius={[0, 4, 4, 0]} />
                <Bar dataKey="speedUp" fill="var(--color-speedUp)" radius={[0, 4, 4, 0]} />
              </BarChart>
            </ChartContainer>
          </CardContent>
        </Card>
      )}

      {/* Plans Grid */}
      {loading ? (
        <div className="grid gap-4 sm:grid-cols-2 lg:grid-cols-3">
          {[...Array(6)].map((_, i) => (
            <Skeleton key={i} className="h-64 rounded-xl" />
          ))}
        </div>
      ) : plans.length === 0 ? (
        <Card className="py-16">
          <CardContent className="text-center">
            <Package className="size-12 mx-auto mb-3 text-muted-foreground opacity-40" />
            <h3 className="text-lg font-semibold">No Plans Found</h3>
            <p className="text-muted-foreground text-sm mt-1">
              Create your first plan to get started
            </p>
            <Button className="mt-4" size="sm" onClick={handleOpenAdd}>
              <Plus className="size-4" />
              Add Plan
            </Button>
          </CardContent>
        </Card>
      ) : (
        <div className="grid gap-4 sm:grid-cols-2 lg:grid-cols-3">
          {plans.map((plan) => (
            <Card key={plan.id} className="relative overflow-hidden gap-0">
              {/* Status indicator bar */}
              <div
                className={`absolute top-0 left-0 right-0 h-1 ${
                  plan.isActive
                    ? 'bg-emerald-500'
                    : 'bg-gray-300 dark:bg-gray-700'
                }`}
              />
              <CardHeader className="pt-6 pb-2">
                <div className="flex items-start justify-between">
                  <div>
                    <CardTitle className="text-lg">{plan.name}</CardTitle>
                    {plan.description && (
                      <CardDescription className="mt-1 line-clamp-2">
                        {plan.description}
                      </CardDescription>
                    )}
                  </div>
                  <div className="flex items-center gap-1">
                    <Badge
                      variant={plan.isActive ? 'default' : 'secondary'}
                      className={plan.isActive ? 'bg-emerald-600 hover:bg-emerald-600' : ''}
                    >
                      {plan.isActive ? 'Active' : 'Inactive'}
                    </Badge>
                  </div>
                </div>
              </CardHeader>
              <CardContent className="space-y-4">
                {/* Price */}
                <div>
                  <div className="text-3xl font-bold">{formatCurrency(plan.price)}</div>
                  <div className="text-xs text-muted-foreground">per {plan.duration} days</div>
                </div>

                {/* Speed Info */}
                <div className="grid grid-cols-2 gap-3">
                  <div className="flex items-center gap-2 rounded-lg bg-muted/50 p-3">
                    <div className="bg-emerald-100 dark:bg-emerald-900/30 rounded-full p-1.5">
                      <ArrowDown className="size-3.5 text-emerald-600 dark:text-emerald-400" />
                    </div>
                    <div>
                      <div className="text-sm font-semibold">{plan.speedDown} Mbps</div>
                      <div className="text-xs text-muted-foreground">Download</div>
                    </div>
                  </div>
                  <div className="flex items-center gap-2 rounded-lg bg-muted/50 p-3">
                    <div className="bg-sky-100 dark:bg-sky-900/30 rounded-full p-1.5">
                      <ArrowUp className="size-3.5 text-sky-600 dark:text-sky-400" />
                    </div>
                    <div>
                      <div className="text-sm font-semibold">{plan.speedUp} Mbps</div>
                      <div className="text-xs text-muted-foreground">Upload</div>
                    </div>
                  </div>
                </div>

                {/* Subscriber count */}
                <div className="flex items-center gap-2 text-sm text-muted-foreground">
                  <Users className="size-4" />
                  <span>
                    <strong className="text-foreground">{plan._count.subscriptions}</strong> active
                    subscribers
                  </span>
                </div>

                {/* Area badge */}
                {plan.area && (
                  <Badge variant="outline" className="text-xs">
                    {plan.area.name}
                  </Badge>
                )}

                {/* Actions */}
                <div className="flex items-center gap-2 pt-2 border-t">
                  <div className="flex items-center gap-2 flex-1">
                    <Label htmlFor={`switch-${plan.id}`} className="text-xs text-muted-foreground cursor-pointer">
                      Active
                    </Label>
                    <Switch
                      id={`switch-${plan.id}`}
                      checked={plan.isActive}
                      onCheckedChange={() => handleToggleActive(plan)}
                    />
                  </div>
                  <Button variant="ghost" size="sm" onClick={() => handleOpenEdit(plan)}>
                    <Pencil className="size-4" />
                  </Button>
                  <Button
                    variant="ghost"
                    size="sm"
                    className="text-red-600 hover:text-red-700 hover:bg-red-50 dark:hover:bg-red-900/20"
                    onClick={() => setDeleteTarget(plan)}
                  >
                    <Trash2 className="size-4" />
                  </Button>
                </div>
              </CardContent>
            </Card>
          ))}
        </div>
      )}

      {/* Add/Edit Plan Dialog */}
      <Dialog open={formOpen} onOpenChange={setFormOpen}>
        <DialogContent className="sm:max-w-lg">
          <DialogHeader>
            <DialogTitle className="flex items-center gap-2">
              {editingPlan ? <Pencil className="size-5" /> : <Plus className="size-5" />}
              {editingPlan ? 'Edit Plan' : 'Add Plan'}
            </DialogTitle>
            <DialogDescription>
              {editingPlan ? 'Update plan details' : 'Create a new internet plan'}
            </DialogDescription>
          </DialogHeader>
          <div className="space-y-4">
            <div>
              <Label>Plan Name *</Label>
              <Input
                className="mt-1.5"
                placeholder="e.g., Basic 10Mbps"
                value={form.name}
                onChange={(e) => setForm((prev) => ({ ...prev, name: e.target.value }))}
              />
            </div>

            <div>
              <Label>Description</Label>
              <Input
                className="mt-1.5"
                placeholder="Brief plan description"
                value={form.description}
                onChange={(e) => setForm((prev) => ({ ...prev, description: e.target.value }))}
              />
            </div>

            <div className="grid grid-cols-2 gap-3">
              <div>
                <Label>Download Speed (Mbps)</Label>
                <Input
                  type="number"
                  className="mt-1.5"
                  placeholder="10"
                  value={form.speedDown}
                  onChange={(e) => setForm((prev) => ({ ...prev, speedDown: e.target.value }))}
                />
              </div>
              <div>
                <Label>Upload Speed (Mbps)</Label>
                <Input
                  type="number"
                  className="mt-1.5"
                  placeholder="5"
                  value={form.speedUp}
                  onChange={(e) => setForm((prev) => ({ ...prev, speedUp: e.target.value }))}
                />
              </div>
            </div>

            <div className="grid grid-cols-2 gap-3">
              <div>
                <Label>Price (৳) *</Label>
                <Input
                  type="number"
                  step="0.01"
                  className="mt-1.5"
                  placeholder="0.00"
                  value={form.price}
                  onChange={(e) => setForm((prev) => ({ ...prev, price: e.target.value }))}
                />
              </div>
              <div>
                <Label>Duration (days)</Label>
                <Input
                  type="number"
                  className="mt-1.5"
                  placeholder="30"
                  value={form.duration}
                  onChange={(e) => setForm((prev) => ({ ...prev, duration: e.target.value }))}
                />
              </div>
            </div>

            <div>
              <Label>Area (Optional)</Label>
              <Select
                value={form.areaId || '__none__'}
                onValueChange={(v) => setForm((prev) => ({ ...prev, areaId: v === '__none__' ? '' : v }))}
              >
                <SelectTrigger className="w-full mt-1.5">
                  <SelectValue placeholder="All Areas" />
                </SelectTrigger>
                <SelectContent>
                  <SelectItem value="__none__">All Areas</SelectItem>
                  {areas.map((area) => (
                    <SelectItem key={area.id} value={area.id}>
                      {area.name}
                    </SelectItem>
                  ))}
                </SelectContent>
              </Select>
            </div>

            <div className="flex items-center gap-3">
              <Switch
                checked={form.isActive}
                onCheckedChange={(checked) => setForm((prev) => ({ ...prev, isActive: checked }))}
              />
              <Label>Active (available for new subscriptions)</Label>
            </div>
          </div>
          <DialogFooter>
            <Button variant="outline" onClick={() => setFormOpen(false)}>
              Cancel
            </Button>
            <Button onClick={handleSubmit} disabled={submitting}>
              {submitting ? (
                <Loader2 className="size-4 animate-spin" />
              ) : editingPlan ? (
                <Pencil className="size-4" />
              ) : (
                <Plus className="size-4" />
              )}
              {editingPlan ? 'Update Plan' : 'Create Plan'}
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>

      {/* Delete Confirmation Dialog */}
      <AlertDialog open={!!deleteTarget} onOpenChange={() => setDeleteTarget(null)}>
        <AlertDialogContent>
          <AlertDialogHeader>
            <AlertDialogTitle>Delete Plan</AlertDialogTitle>
            <AlertDialogDescription>
              Are you sure you want to delete &quot;{deleteTarget?.name}&quot;? This action cannot be
              undone. Plans with active subscriptions 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>
  )
}
