'use client'

import { useState, useEffect, useCallback } from 'react'
import {
  UserPlus,
  Loader2,
  Mail,
  Phone,
  Lock,
  User,
  Globe,
  Wifi,
  MapPin,
} from 'lucide-react'
import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogFooter,
  DialogHeader,
  DialogTitle,
} from '@/components/ui/dialog'
import { Button } from '@/components/ui/button'
import { Input } from '@/components/ui/input'
import { Label } from '@/components/ui/label'
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from '@/components/ui/select'
import { useToast } from '@/hooks/use-toast'
import { api } from '@/lib/api'

interface Area {
  id: string
  name: string
}

interface Plan {
  id: string
  name: string
  price: number
  duration: number
  speedDown: number
  speedUp: number
}

interface Reseller {
  id: string
  user: { id: string; name: string; email: string }
  isActive: boolean
}

interface AddClientDialogProps {
  open: boolean
  onOpenChange: (open: boolean) => void
}

const CONNECTION_TYPES = [
  { value: 'FIBER', label: 'Fiber' },
  { value: 'WIRELESS', label: 'Wireless' },
  { value: 'DIALUP', label: 'Dial-up' },
  { value: 'ETHERNET', label: 'Ethernet' },
]

const defaultForm = {
  name: '',
  email: '',
  phone: '',
  password: '',
  username: '',
  areaId: '',
  connectionType: 'FIBER',
  ipAddress: '',
  macAddress: '',
  address: '',
  resellerId: '',
  planId: '',
}

export default function AddClientDialog({ open, onOpenChange }: AddClientDialogProps) {
  const { toast } = useToast()
  const [submitting, setSubmitting] = useState(false)
  const [form, setForm] = useState(defaultForm)
  const [errors, setErrors] = useState<Record<string, string>>({})

  const [areas, setAreas] = useState<Area[]>([])
  const [plans, setPlans] = useState<Plan[]>([])
  const [resellers, setResellers] = useState<Reseller[]>([])
  const [loadingDropdowns, setLoadingDropdowns] = useState(false)

  const fetchDropdowns = useCallback(async () => {
    try {
      setLoadingDropdowns(true)
      const [areasRes, plansRes, resellersRes] = await Promise.all([
        api.get<{ success: boolean; data: { areas: Area[] } }>('/api/areas?limit=50'),
        api.get<{ success: boolean; data: { plans: Plan[] } }>('/api/plans?isActive=true&limit=50'),
        api.get<{ success: boolean; data: { resellers: Reseller[] } }>('/api/resellers?limit=50'),
      ])

      if (areasRes.success) setAreas(areasRes.data.areas)
      if (plansRes.success) setPlans(plansRes.data.plans)
      if (resellersRes.success) setResellers(resellersRes.data.resellers)
    } catch {
      // silent
    } finally {
      setLoadingDropdowns(false)
    }
  }, [])

  useEffect(() => {
    if (open) {
      fetchDropdowns()
      setForm(defaultForm)
      setErrors({})
    }
  }, [open, fetchDropdowns])

  const validate = (): boolean => {
    const newErrors: Record<string, string> = {}

    if (!form.name.trim()) newErrors.name = 'Name is required'
    if (!form.email.trim()) newErrors.email = 'Email is required'
    else if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(form.email))
      newErrors.email = 'Invalid email format'
    if (!form.password.trim()) newErrors.password = 'Password is required'
    else if (form.password.length < 6) newErrors.password = 'Password must be at least 6 characters'

    setErrors(newErrors)
    return Object.keys(newErrors).length === 0
  }

  const handleSubmit = async () => {
    if (!validate()) return

    try {
      setSubmitting(true)

      // Step 1: Register user
      const registerRes = await api.post<{
        success: boolean
        data: { user: { id: string }; token: string }
        error?: string
      }>('/api/auth/register', {
        name: form.name,
        email: form.email,
        password: form.password,
        phone: form.phone,
        username: form.username,
        areaId: form.areaId || undefined,
        connectionType: form.connectionType,
        ipAddress: form.ipAddress,
        macAddress: form.macAddress,
        address: form.address,
        resellerId: form.resellerId || undefined,
      })

      if (!registerRes.success) {
        toast({
          title: 'Registration Failed',
          description: registerRes.error || 'Failed to register user',
          variant: 'destructive',
        })
        return
      }

      const userId = registerRes.data.user.id

      // Step 2: Create subscription if plan selected
      if (form.planId) {
        try {
          await api.post('/api/subscriptions', {
            userId,
            planId: form.planId,
          })
        } catch {
          toast({
            title: 'Warning',
            description: 'User created but subscription failed',
            variant: 'destructive',
          })
          return
        }
      }

      toast({
        title: 'Client Added',
        description: `${form.name} has been registered successfully${form.planId ? ' with a subscription' : ''}`,
      })

      onOpenChange(false)
    } catch (err) {
      toast({
        title: 'Error',
        description: err instanceof Error ? err.message : 'Failed to add client',
        variant: 'destructive',
      })
    } finally {
      setSubmitting(false)
    }
  }

  const updateField = (field: string, value: string) => {
    setForm((prev) => ({ ...prev, [field]: value }))
    if (errors[field]) {
      setErrors((prev) => {
        const next = { ...prev }
        delete next[field]
        return next
      })
    }
  }

  return (
    <Dialog open={open} onOpenChange={onOpenChange}>
      <DialogContent className="sm:max-w-2xl max-h-[90vh] overflow-y-auto">
        <DialogHeader>
          <DialogTitle className="flex items-center gap-2">
            <UserPlus className="size-5" />
            Add New Client
          </DialogTitle>
          <DialogDescription>
            Register a new client and optionally assign a subscription plan
          </DialogDescription>
        </DialogHeader>

        <div className="space-y-5">
          {/* Personal Information */}
          <div>
            <h3 className="text-sm font-semibold mb-3 flex items-center gap-2">
              <User className="size-4 text-muted-foreground" />
              Personal Information
            </h3>
            <div className="grid grid-cols-1 sm:grid-cols-2 gap-3">
              <div>
                <Label htmlFor="name">
                  Full Name <span className="text-red-500">*</span>
                </Label>
                <div className="relative mt-1.5">
                  <User className="absolute left-2.5 top-2.5 size-4 text-muted-foreground" />
                  <Input
                    id="name"
                    placeholder="John Doe"
                    className={`pl-9 ${errors.name ? 'border-red-500' : ''}`}
                    value={form.name}
                    onChange={(e) => updateField('name', e.target.value)}
                  />
                </div>
                {errors.name && (
                  <p className="text-xs text-red-500 mt-1">{errors.name}</p>
                )}
              </div>

              <div>
                <Label htmlFor="email">
                  Email <span className="text-red-500">*</span>
                </Label>
                <div className="relative mt-1.5">
                  <Mail className="absolute left-2.5 top-2.5 size-4 text-muted-foreground" />
                  <Input
                    id="email"
                    type="email"
                    placeholder="client@example.com"
                    className={`pl-9 ${errors.email ? 'border-red-500' : ''}`}
                    value={form.email}
                    onChange={(e) => updateField('email', e.target.value)}
                  />
                </div>
                {errors.email && (
                  <p className="text-xs text-red-500 mt-1">{errors.email}</p>
                )}
              </div>

              <div>
                <Label htmlFor="phone">Phone</Label>
                <div className="relative mt-1.5">
                  <Phone className="absolute left-2.5 top-2.5 size-4 text-muted-foreground" />
                  <Input
                    id="phone"
                    placeholder="+1 234 567 890"
                    className="pl-9"
                    value={form.phone}
                    onChange={(e) => updateField('phone', e.target.value)}
                  />
                </div>
              </div>

              <div>
                <Label htmlFor="username">Username</Label>
                <div className="relative mt-1.5">
                  <Globe className="absolute left-2.5 top-2.5 size-4 text-muted-foreground" />
                  <Input
                    id="username"
                    placeholder="johndoe"
                    className="pl-9"
                    value={form.username}
                    onChange={(e) => updateField('username', e.target.value)}
                  />
                </div>
              </div>

              <div className="sm:col-span-2">
                <Label htmlFor="password">
                  Password <span className="text-red-500">*</span>
                </Label>
                <div className="relative mt-1.5">
                  <Lock className="absolute left-2.5 top-2.5 size-4 text-muted-foreground" />
                  <Input
                    id="password"
                    type="password"
                    placeholder="Min 6 characters"
                    className={`pl-9 ${errors.password ? 'border-red-500' : ''}`}
                    value={form.password}
                    onChange={(e) => updateField('password', e.target.value)}
                  />
                </div>
                {errors.password && (
                  <p className="text-xs text-red-500 mt-1">{errors.password}</p>
                )}
              </div>
            </div>
          </div>

          {/* Connection & Network */}
          <div>
            <h3 className="text-sm font-semibold mb-3 flex items-center gap-2">
              <Wifi className="size-4 text-muted-foreground" />
              Connection & Network
            </h3>
            <div className="grid grid-cols-1 sm:grid-cols-2 gap-3">
              <div>
                <Label>Area</Label>
                <Select
                  value={form.areaId || '__none__'}
                  onValueChange={(v) => updateField('areaId', v === '__none__' ? '' : v)}
                >
                  <SelectTrigger className="w-full mt-1.5">
                    <SelectValue placeholder="Select area" />
                  </SelectTrigger>
                  <SelectContent>
                    <SelectItem value="__none__">No Area</SelectItem>
                    {areas.map((area) => (
                      <SelectItem key={area.id} value={area.id}>
                        {area.name}
                      </SelectItem>
                    ))}
                  </SelectContent>
                </Select>
              </div>

              <div>
                <Label>Connection Type</Label>
                <Select
                  value={form.connectionType}
                  onValueChange={(v) => updateField('connectionType', v)}
                >
                  <SelectTrigger className="w-full mt-1.5">
                    <SelectValue />
                  </SelectTrigger>
                  <SelectContent>
                    {CONNECTION_TYPES.map((ct) => (
                      <SelectItem key={ct.value} value={ct.value}>
                        {ct.label}
                      </SelectItem>
                    ))}
                  </SelectContent>
                </Select>
              </div>

              <div>
                <Label>IP Address</Label>
                <Input
                  placeholder="192.168.1.100"
                  className="mt-1.5"
                  value={form.ipAddress}
                  onChange={(e) => updateField('ipAddress', e.target.value)}
                />
              </div>

              <div>
                <Label>MAC Address</Label>
                <Input
                  placeholder="AA:BB:CC:DD:EE:FF"
                  className="mt-1.5"
                  value={form.macAddress}
                  onChange={(e) => updateField('macAddress', e.target.value)}
                />
              </div>

              <div className="sm:col-span-2">
                <Label>Address</Label>
                <div className="relative mt-1.5">
                  <MapPin className="absolute left-2.5 top-2.5 size-4 text-muted-foreground" />
                  <Input
                    placeholder="Full street address"
                    className="pl-9"
                    value={form.address}
                    onChange={(e) => updateField('address', e.target.value)}
                  />
                </div>
              </div>
            </div>
          </div>

          {/* Reseller */}
          <div>
            <h3 className="text-sm font-semibold mb-3 flex items-center gap-2">
              <UserPlus className="size-4 text-muted-foreground" />
              Reseller (Optional)
            </h3>
            <Select
              value={form.resellerId || '__none__'}
              onValueChange={(v) => updateField('resellerId', v === '__none__' ? '' : v)}
            >
              <SelectTrigger className="w-full">
                <SelectValue placeholder="Assign to reseller" />
              </SelectTrigger>
              <SelectContent>
                <SelectItem value="__none__">No Reseller</SelectItem>
                {resellers.map((reseller) => (
                  <SelectItem key={reseller.id} value={reseller.id}>
                    {reseller.user.name} ({reseller.user.email})
                  </SelectItem>
                ))}
              </SelectContent>
            </Select>
          </div>

          {/* Plan Selection */}
          <div>
            <h3 className="text-sm font-semibold mb-3 flex items-center gap-2">
              <Lock className="size-4 text-muted-foreground" />
              Subscription Plan (Optional)
            </h3>
            <Select
              value={form.planId || '__none__'}
              onValueChange={(v) => updateField('planId', v === '__none__' ? '' : v)}
            >
              <SelectTrigger className="w-full">
                <SelectValue placeholder="Select a plan" />
              </SelectTrigger>
              <SelectContent className="max-h-64">
                <SelectItem value="__none__">No Plan (Register Only)</SelectItem>
                {plans.map((plan) => (
                  <SelectItem key={plan.id} value={plan.id}>
                    <div className="flex items-center justify-between gap-6 w-full">
                      <span>{plan.name}</span>
                      <span className="text-xs text-muted-foreground">
                        ৳{plan.price}/{plan.duration}d • {plan.speedDown}/{plan.speedUp} Mbps
                      </span>
                    </div>
                  </SelectItem>
                ))}
              </SelectContent>
            </Select>
            {form.planId && (
              <p className="text-xs text-muted-foreground mt-2">
                A subscription will be automatically created after registration.
              </p>
            )}
          </div>
        </div>

        <DialogFooter>
          <Button variant="outline" onClick={() => onOpenChange(false)} disabled={submitting}>
            Cancel
          </Button>
          <Button onClick={handleSubmit} disabled={submitting}>
            {submitting ? (
              <Loader2 className="size-4 animate-spin" />
            ) : (
              <UserPlus className="size-4" />
            )}
            Add Client
          </Button>
        </DialogFooter>
      </DialogContent>
    </Dialog>
  )
}
