import { createFileRoute, useNavigate } 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 '@forte/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 { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select'
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card'
import { ArrowLeft } from 'lucide-react'
import { toast } from 'sonner'

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

function NewRepairBatchPage() {
  const navigate = useNavigate()

  const { data: accountsData } = useQuery(accountListOptions({ page: 1, limit: 100, order: 'asc', sort: 'name' }))

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

  const mutation = useMutation({
    mutationFn: repairBatchMutations.create,
    onSuccess: (batch) => {
      toast.success('Repair batch created')
      navigate({ to: '/repair-batches/$batchId', params: { batchId: batch.id }, search: {} as any })
    },
    onError: (err) => toast.error(err.message),
  })

  const accounts = accountsData?.data ?? []

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

      <Card>
        <CardHeader>
          <CardTitle className="text-lg">Batch Details</CardTitle>
        </CardHeader>
        <CardContent>
          <form onSubmit={handleSubmit((data) => mutation.mutate(data))} className="space-y-4">
            <div className="space-y-2">
              <Label>Account (School) *</Label>
              <Select onValueChange={(v) => setValue('accountId', v)}>
                <SelectTrigger>
                  <SelectValue placeholder="Select account" />
                </SelectTrigger>
                <SelectContent>
                  {accounts.map((a: { id: string; name: string }) => (
                    <SelectItem key={a.id} value={a.id}>{a.name}</SelectItem>
                  ))}
                </SelectContent>
              </Select>
              {errors.accountId && <p className="text-sm text-destructive">{errors.accountId.message}</p>}
            </div>

            <div className="grid 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="grid grid-cols-2 gap-4">
              <div className="space-y-2">
                <Label>Contact Email</Label>
                <Input type="email" {...register('contactEmail')} />
              </div>
              <div className="space-y-2">
                <Label>Instrument Count</Label>
                <Input type="number" {...register('instrumentCount', { valueAsNumber: true })} />
              </div>
            </div>

            <div className="space-y-2">
              <Label>Notes</Label>
              <Textarea {...register('notes')} rows={3} placeholder="e.g. Annual instrument checkup for band program" />
            </div>

            <div className="flex gap-2">
              <Button type="submit" disabled={mutation.isPending}>
                {mutation.isPending ? 'Creating...' : 'Create Batch'}
              </Button>
              <Button variant="secondary" type="button" onClick={() => navigate({ to: '/repair-batches', search: {} as any })}>
                Cancel
              </Button>
            </div>
          </form>
        </CardContent>
      </Card>
    </div>
  )
}
