import { useForm } from 'react-hook-form'
import { useRef, useState } from 'react'
import { Button } from '@/components/ui/button'
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 type { MemberIdentifier } from '@/types/account'
import { Upload, X } from 'lucide-react'

const ID_TYPES = [
  { value: 'drivers_license', label: "Driver's License / State ID" },
  { value: 'passport', label: 'Passport' },
  { value: 'school_id', label: 'School ID' },
]

export interface IdentifierFiles {
  front?: File
  back?: File
}

interface IdentifierFormProps {
  memberId: string
  defaultValues?: Partial<MemberIdentifier>
  onSubmit: (data: Record<string, unknown>, files: IdentifierFiles) => void
  loading?: boolean
}

export function IdentifierForm({ memberId, defaultValues, onSubmit, loading }: IdentifierFormProps) {
  const { register, handleSubmit, setValue, watch } = useForm({
    defaultValues: {
      type: defaultValues?.type ?? 'drivers_license',
      value: defaultValues?.value ?? '',
      label: defaultValues?.label ?? '',
      issuingAuthority: defaultValues?.issuingAuthority ?? '',
      issuedDate: defaultValues?.issuedDate ?? '',
      expiresAt: defaultValues?.expiresAt ?? '',
      notes: defaultValues?.notes ?? '',
      isPrimary: defaultValues?.isPrimary ?? false,
    },
  })

  const frontInputRef = useRef<HTMLInputElement>(null)
  const backInputRef = useRef<HTMLInputElement>(null)
  const [frontFile, setFrontFile] = useState<File | null>(null)
  const [backFile, setBackFile] = useState<File | null>(null)
  const [frontPreview, setFrontPreview] = useState<string | null>(null)
  const [backPreview, setBackPreview] = useState<string | null>(null)
  const idType = watch('type')

  function handleFileSelect(side: 'front' | 'back', file: File) {
    const url = URL.createObjectURL(file)
    if (side === 'front') {
      setFrontFile(file)
      setFrontPreview(url)
    } else {
      setBackFile(file)
      setBackPreview(url)
    }
  }

  function clearFile(side: 'front' | 'back') {
    if (side === 'front') {
      if (frontPreview) URL.revokeObjectURL(frontPreview)
      setFrontFile(null)
      setFrontPreview(null)
    } else {
      if (backPreview) URL.revokeObjectURL(backPreview)
      setBackFile(null)
      setBackPreview(null)
    }
  }

  function handleFormSubmit(data: Record<string, unknown>) {
    const cleaned: Record<string, unknown> = { memberId }
    for (const [key, value] of Object.entries(data)) {
      cleaned[key] = value === '' ? undefined : value
    }
    onSubmit(cleaned, {
      front: frontFile ?? undefined,
      back: backFile ?? undefined,
    })
  }

  return (
    <form onSubmit={handleSubmit(handleFormSubmit)} noValidate className="space-y-4">
      <div className="space-y-2">
        <Label>ID Type *</Label>
        <Select value={idType} onValueChange={(v: string) => setValue('type', v as 'drivers_license' | 'passport' | 'school_id')}>
          <SelectTrigger>
            <SelectValue />
          </SelectTrigger>
          <SelectContent>
            {ID_TYPES.map((t) => (
              <SelectItem key={t.value} value={t.value}>{t.label}</SelectItem>
            ))}
          </SelectContent>
        </Select>
      </div>

      <div className="space-y-2">
        <Label htmlFor="idValue">ID Number *</Label>
        <Input id="idValue" {...register('value', { required: true })} placeholder="e.g. DL12345678" />
      </div>

      <div className="grid grid-cols-2 gap-4">
        <div className="space-y-2">
          <Label htmlFor="issuingAuthority">Issuing Authority</Label>
          <Input id="issuingAuthority" {...register('issuingAuthority')} placeholder="e.g. State of Texas" />
        </div>
        <div className="space-y-2">
          <Label htmlFor="idLabel">Label</Label>
          <Input id="idLabel" {...register('label')} placeholder="e.g. Primary ID" />
        </div>
      </div>

      <div className="grid grid-cols-2 gap-4">
        <div className="space-y-2">
          <Label htmlFor="issuedDate">Issued Date</Label>
          <Input id="issuedDate" type="date" {...register('issuedDate')} />
        </div>
        <div className="space-y-2">
          <Label htmlFor="expiresAt">Expires</Label>
          <Input id="expiresAt" type="date" {...register('expiresAt')} />
        </div>
      </div>

      <div className="grid grid-cols-2 gap-4">
        <div className="space-y-2">
          <Label>Front Image</Label>
          <input
            ref={frontInputRef}
            type="file"
            accept="image/jpeg,image/png,image/webp"
            className="hidden"
            onChange={(e) => e.target.files?.[0] && handleFileSelect('front', e.target.files[0])}
          />
          {frontPreview ? (
            <div className="relative">
              <img src={frontPreview} alt="ID front" className="rounded-md border max-h-32 w-full object-cover" />
              <Button
                type="button"
                variant="secondary"
                size="sm"
                className="absolute top-1 right-1 h-6 w-6 p-0"
                onClick={() => clearFile('front')}
              >
                <X className="h-3 w-3" />
              </Button>
            </div>
          ) : (
            <Button type="button" variant="outline" className="w-full" onClick={() => frontInputRef.current?.click()}>
              <Upload className="mr-2 h-4 w-4" /> Upload Front
            </Button>
          )}
        </div>
        <div className="space-y-2">
          <Label>Back Image</Label>
          <input
            ref={backInputRef}
            type="file"
            accept="image/jpeg,image/png,image/webp"
            className="hidden"
            onChange={(e) => e.target.files?.[0] && handleFileSelect('back', e.target.files[0])}
          />
          {backPreview ? (
            <div className="relative">
              <img src={backPreview} alt="ID back" className="rounded-md border max-h-32 w-full object-cover" />
              <Button
                type="button"
                variant="secondary"
                size="sm"
                className="absolute top-1 right-1 h-6 w-6 p-0"
                onClick={() => clearFile('back')}
              >
                <X className="h-3 w-3" />
              </Button>
            </div>
          ) : (
            <Button type="button" variant="outline" className="w-full" onClick={() => backInputRef.current?.click()}>
              <Upload className="mr-2 h-4 w-4" /> Upload Back
            </Button>
          )}
        </div>
      </div>

      <div className="flex items-center gap-2">
        <input type="checkbox" id="isPrimary" {...register('isPrimary')} className="rounded" />
        <Label htmlFor="isPrimary" className="font-normal">Primary ID</Label>
      </div>

      <div className="space-y-2">
        <Label htmlFor="idNotes">Notes</Label>
        <Textarea id="idNotes" {...register('notes')} />
      </div>

      <Button type="submit" disabled={loading}>
        {loading ? 'Saving...' : defaultValues ? 'Update ID' : 'Add ID'}
      </Button>
    </form>
  )
}
