import { useState } from 'react'
import { createFileRoute, useNavigate, Link } from '@tanstack/react-router'
import { useQuery, useMutation } from '@tanstack/react-query'
import { useForm } from 'react-hook-form'
import { zodResolver } from '@hookform/resolvers/zod'
import { RepairBatchCreateSchema } from '@lunarfront/shared/schemas'
import { repairBatchMutations } from '@/api/repairs'
import { accountListOptions } from '@/api/accounts'
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 { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card'
import { ArrowLeft, Search, Plus, X } from 'lucide-react'
import { toast } from 'sonner'
import type { Account } from '@/types/account'

export const Route = createFileRoute('/_authenticated/repair-batches/new')({
  component: NewRepairBatchPage,
})

function NewRepairBatchPage() {
  const navigate = useNavigate()

  const [accountSearch, setAccountSearch] = useState('')
  const [selectedAccount, setSelectedAccount] = useState<Account | null>(null)
  const [showAccountDropdown, setShowAccountDropdown] = useState(false)

  const { data: accountsData } = useQuery(
    accountListOptions({ page: 1, limit: 20, q: accountSearch || undefined, order: 'asc', sort: 'name' }),
  )

  const {
    register,
    handleSubmit,
    setValue,
    formState: { errors },
  } = useForm({
    resolver: zodResolver(RepairBatchCreateSchema),
    defaultValues: {
      accountId: '',
      contactName: '',
      contactPhone: '',
      contactEmail: '',
      notes: '',
    },
  })

  const mutation = useMutation({
    mutationFn: repairBatchMutations.create,
    onSuccess: (batch) => {
      toast.success('Repair batch created')
      navigate({ to: '/repair-batches/$batchId', params: { batchId: batch.id }, search: { page: 1, limit: 25, q: undefined, sort: undefined, order: 'asc' as const } })
    },
    onError: (err) => toast.error(err.message),
  })

  function selectAccount(account: Account) {
    setSelectedAccount(account)
    setShowAccountDropdown(false)
    setAccountSearch('')
    setValue('accountId', account.id)
    if (account.phone) setValue('contactPhone', account.phone)
    if (account.email) setValue('contactEmail', account.email)
    setValue('contactName', account.name)
  }

  function clearAccount() {
    setSelectedAccount(null)
    setValue('accountId', '')
    setValue('contactName', '')
    setValue('contactPhone', '')
    setValue('contactEmail', '')
  }

  const accounts = accountsData?.data ?? []

  return (
    <div className="space-y-6 max-w-3xl">
      <div className="flex items-center gap-3">
        <Button variant="ghost" size="sm" onClick={() => navigate({ to: '/repair-batches', search: { page: 1, limit: 25, q: undefined, sort: undefined, order: 'asc' as const } })}>
          <ArrowLeft className="h-4 w-4" />
        </Button>
        <h1 className="text-2xl font-bold">New Repair Batch</h1>
      </div>

      <form onSubmit={handleSubmit((data) => mutation.mutate(data))} className="space-y-6">
        <Card>
          <CardHeader>
            <div className="flex items-center justify-between">
              <CardTitle className="text-lg">Account</CardTitle>
              <Link to="/accounts/new" className="text-sm text-primary hover:underline flex items-center gap-1">
                <Plus className="h-3 w-3" />New Account
              </Link>
            </div>
          </CardHeader>
          <CardContent className="space-y-4">
            {!selectedAccount ? (
              <div className="relative">
                <Label>Search Account</Label>
                <div className="relative mt-1">
                  <Search className="absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground" />
                  <Input
                    placeholder="Type to search by name, email, or phone..."
                    value={accountSearch}
                    onChange={(e) => { setAccountSearch(e.target.value); setShowAccountDropdown(true) }}
                    onFocus={() => setShowAccountDropdown(true)}
                    className="pl-9"
                  />
                </div>
                {showAccountDropdown && accountSearch.length > 0 && (
                  <div className="absolute z-50 mt-1 w-full rounded-md border bg-popover shadow-lg max-h-60 overflow-auto">
                    {accounts.length === 0 ? (
                      <div className="p-3 text-sm text-muted-foreground">No accounts found</div>
                    ) : (
                      accounts.map((a) => (
                        <button key={a.id} type="button" className="w-full text-left px-3 py-2 text-sm hover:bg-accent flex items-center justify-between" onClick={() => selectAccount(a)}>
                          <div>
                            <span className="font-medium">{a.name}</span>
                            {a.email && <span className="text-muted-foreground ml-2">{a.email}</span>}
                            {a.phone && <span className="text-muted-foreground ml-2">{a.phone}</span>}
                          </div>
                          {a.accountNumber && <span className="text-xs text-muted-foreground font-mono">#{a.accountNumber}</span>}
                        </button>
                      ))
                    )}
                  </div>
                )}
                {errors.accountId && <p className="text-sm text-destructive mt-1">{errors.accountId.message}</p>}
              </div>
            ) : (
              <div className="flex items-center justify-between p-3 rounded-md border bg-muted/30">
                <div>
                  <p className="font-medium">{selectedAccount.name}</p>
                  <div className="flex gap-4 text-sm text-muted-foreground">
                    {selectedAccount.phone && <span>{selectedAccount.phone}</span>}
                    {selectedAccount.email && <span>{selectedAccount.email}</span>}
                    {selectedAccount.accountNumber && <span className="font-mono">#{selectedAccount.accountNumber}</span>}
                  </div>
                </div>
                <Button type="button" variant="ghost" size="sm" onClick={clearAccount}><X className="h-4 w-4" /></Button>
              </div>
            )}
          </CardContent>
        </Card>

        <Card>
          <CardHeader>
            <CardTitle className="text-lg">Contact & Details</CardTitle>
          </CardHeader>
          <CardContent className="space-y-4">
            <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
              <div className="space-y-2">
                <Label>Contact Name</Label>
                <Input {...register('contactName')} />
              </div>
              <div className="space-y-2">
                <Label>Contact Phone</Label>
                <Input {...register('contactPhone')} />
              </div>
            </div>

            <div className="space-y-2">
              <Label>Contact Email</Label>
              <Input type="email" {...register('contactEmail')} />
            </div>

            <div className="space-y-2">
              <Label>Notes</Label>
              <Textarea {...register('notes')} rows={3} placeholder="e.g. Annual checkup, multiple items needing service" />
            </div>
          </CardContent>
        </Card>

        <div className="flex gap-2">
          <Button type="submit" disabled={mutation.isPending} size="lg">
            {mutation.isPending ? 'Creating...' : 'Create Batch'}
          </Button>
          <Button variant="secondary" type="button" size="lg" onClick={() => navigate({ to: '/repair-batches', search: { page: 1, limit: 25, q: undefined, sort: undefined, order: 'asc' as const } })}>
            Cancel
          </Button>
        </div>
      </form>
    </div>
  )
}
