import { useState, useRef } 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 { RepairTicketCreateSchema } from '@lunarfront/shared/schemas'
import { repairTicketMutations, repairLineItemMutations, repairServiceTemplateListOptions } from '@/api/repairs'
import { accountListOptions } from '@/api/accounts'
import { useAuthStore } from '@/stores/auth.store'
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 { Badge } from '@/components/ui/badge'
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select'
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card'
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from '@/components/ui/table'
import { ArrowLeft, Search, Plus, X, ImageIcon, Trash2 } from 'lucide-react'
import { toast } from 'sonner'
import type { Account } from '@/types/account'

interface PendingLineItem {
  itemType: string
  description: string
  qty: number
  unitPrice: number
  totalPrice: number
  cost?: number
}

export const Route = createFileRoute('/_authenticated/repairs/new')({
  validateSearch: (search: Record<string, unknown>) => ({
    batchId: (search.batchId as string) || undefined,
    batchName: (search.batchName as string) || undefined,
    accountId: (search.accountId as string) || undefined,
    contactName: (search.contactName as string) || undefined,
  }),
  component: NewRepairPage,
})

function NewRepairPage() {
  const navigate = useNavigate()
  const token = useAuthStore((s) => s.token)
  const search = Route.useSearch()
  const linkedBatchId = search.batchId
  const linkedBatchName = search.batchName
  const linkedAccountId = search.accountId
  const linkedContactName = search.contactName

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

  // Line items built during intake
  const [lineItems, setLineItems] = useState<PendingLineItem[]>([])

  // Template search for adding line items
  const [templateSearch, setTemplateSearch] = useState('')
  const [showTemplates, setShowTemplates] = useState(false)

  // Manual line item fields
  const [manualType, setManualType] = useState('labor')
  const [manualDesc, setManualDesc] = useState('')
  const [manualQty, setManualQty] = useState('1')
  const [manualPrice, setManualPrice] = useState('0')
  const [manualCost, setManualCost] = useState('')

  // Photos
  const [photos, setPhotos] = useState<File[]>([])
  const photoInputRef = useRef<HTMLInputElement>(null)

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

  const { data: templatesData } = useQuery(
    repairServiceTemplateListOptions({ page: 1, limit: 20, q: templateSearch || undefined, order: 'asc', sort: 'name' }),
  )

  const {
    register,
    handleSubmit,
    setValue,
    formState: { errors },
  } = useForm({
    resolver: zodResolver(RepairTicketCreateSchema),
    defaultValues: {
      customerName: linkedContactName ?? '',
      customerPhone: '',
      itemDescription: '',
      serialNumber: '',
      problemDescription: '',
      conditionIn: undefined,
      estimatedCost: undefined,
      accountId: linkedAccountId ?? undefined,
    },
  })

  // Auto-calculate estimated cost from line items
  const estimatedTotal = lineItems.reduce((sum, item) => sum + item.totalPrice, 0)

  const mutation = useMutation({
    mutationFn: async (data: Record<string, unknown>) => {
      // Set estimated cost from line items if any
      if (lineItems.length > 0) {
        data.estimatedCost = estimatedTotal
      }
      // Link to batch if coming from a batch
      if (linkedBatchId) {
        data.repairBatchId = linkedBatchId
      }

      const ticket = await repairTicketMutations.create(data)

      // Create line items
      for (const item of lineItems) {
        await repairLineItemMutations.create(ticket.id, item as unknown as Record<string, unknown>)
      }

      // Upload photos
      for (const photo of photos) {
        const formData = new FormData()
        formData.append('file', photo)
        formData.append('entityType', 'repair_ticket')
        formData.append('entityId', ticket.id)
        formData.append('category', 'intake')
        await fetch('/v1/files', {
          method: 'POST',
          headers: { Authorization: `Bearer ${token}` },
          body: formData,
        })
      }

      return ticket
    },
    onSuccess: (ticket) => {
      toast.success('Repair ticket created')
      navigate({ to: '/repairs/$ticketId', params: { ticketId: ticket.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)
    setValue('customerName', account.name)
    setValue('customerPhone', account.phone ?? '')
  }

  function clearAccount() {
    setSelectedAccount(null)
    setValue('accountId', undefined)
    setValue('customerName', '')
    setValue('customerPhone', '')
  }

  function addFromTemplate(template: { name: string; itemCategory: string | null; size: string | null; itemType: string; defaultPrice: string; defaultCost: string | null }) {
    const desc = [template.name, template.itemCategory, template.size].filter(Boolean).join(' — ')
    setLineItems((prev) => [...prev, {
      itemType: template.itemType,
      description: desc,
      qty: 1,
      unitPrice: parseFloat(template.defaultPrice),
      totalPrice: parseFloat(template.defaultPrice),
      cost: template.defaultCost ? parseFloat(template.defaultCost) : undefined,
    }])
    setTemplateSearch('')
    setShowTemplates(false)
  }

  function addManualItem() {
    if (!manualDesc.trim()) return
    const q = parseFloat(manualQty) || 1
    const p = parseFloat(manualPrice) || 0
    const c = manualCost ? parseFloat(manualCost) : undefined
    setLineItems((prev) => [...prev, {
      itemType: manualType,
      description: manualDesc,
      qty: q,
      unitPrice: p,
      totalPrice: q * p,
      cost: c,
    }])
    setManualDesc('')
    setManualQty('1')
    setManualPrice('0')
    setManualCost('')
  }

  function removeLineItem(index: number) {
    setLineItems((prev) => prev.filter((_, i) => i !== index))
  }

  function addPhotos(e: React.ChangeEvent<HTMLInputElement>) {
    const files = Array.from(e.target.files ?? [])
    setPhotos((prev) => [...prev, ...files])
    e.target.value = ''
  }

  function removePhoto(index: number) {
    setPhotos((prev) => prev.filter((_, i) => i !== index))
  }

  const accounts = accountsData?.data ?? []
  const templates = templatesData?.data ?? []

  return (
    <div className="space-y-6 max-w-4xl">
      <div className="flex items-center gap-3">
        <Button variant="ghost" size="sm" onClick={() => navigate({ to: '/repairs', 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 Ticket</h1>
      </div>

      {linkedBatchId && (
        <div className="flex items-center gap-2 px-3 py-2 rounded-md border bg-muted/30 text-sm">
          <Badge variant="outline">Batch #{linkedBatchName}</Badge>
          <span className="text-muted-foreground">This repair will be linked to the batch</span>
        </div>
      )}

      <form onSubmit={handleSubmit((data) => mutation.mutate(data))} className="space-y-6">
        {/* Customer Section */}
        <Card>
          <CardHeader>
            <div className="flex items-center justify-between">
              <CardTitle className="text-lg">Customer</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>
                )}
                <p className="text-xs text-muted-foreground mt-1">Or fill in customer details manually below for walk-ins</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>
            )}

            <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
              <div className="space-y-2">
                <Label>Customer Name *</Label>
                <Input {...register('customerName')} />
                {errors.customerName && <p className="text-sm text-destructive">{errors.customerName.message}</p>}
              </div>
              <div className="space-y-2">
                <Label>Phone</Label>
                <Input {...register('customerPhone')} />
              </div>
            </div>
          </CardContent>
        </Card>

        {/* Item Section */}
        <Card>
          <CardHeader><CardTitle className="text-lg">Item</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>Item Description</Label>
                <Input {...register('itemDescription')} placeholder="e.g. Brand, model, description" />
              </div>
              <div className="space-y-2">
                <Label>Serial Number</Label>
                <Input {...register('serialNumber')} />
              </div>
            </div>
            <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
              <div className="space-y-2">
                <Label>Condition at Intake</Label>
                <Select onValueChange={(v) => setValue('conditionIn', v as 'excellent' | 'good' | 'fair' | 'poor')}>
                  <SelectTrigger><SelectValue placeholder="Select condition" /></SelectTrigger>
                  <SelectContent>
                    <SelectItem value="excellent">Excellent</SelectItem>
                    <SelectItem value="good">Good</SelectItem>
                    <SelectItem value="fair">Fair</SelectItem>
                    <SelectItem value="poor">Poor</SelectItem>
                  </SelectContent>
                </Select>
              </div>
              <div className="space-y-2">
                <Label>Problem Description *</Label>
                <Textarea {...register('problemDescription')} rows={2} placeholder="Describe the issue..." />
                {errors.problemDescription && <p className="text-sm text-destructive">{errors.problemDescription.message}</p>}
              </div>
            </div>
          </CardContent>
        </Card>

        {/* Estimate / Line Items Section */}
        <Card>
          <CardHeader>
            <div className="flex items-center justify-between">
              <CardTitle className="text-lg">Estimate</CardTitle>
              {lineItems.length > 0 && (
                <span className="text-lg font-semibold text-primary">${estimatedTotal.toFixed(2)}</span>
              )}
            </div>
          </CardHeader>
          <CardContent className="space-y-4">
            {/* Template search */}
            <div className="relative">
              <Label>Quick Add from Template</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="Search templates (e.g. rehair, strings, valve)..."
                  value={templateSearch}
                  onChange={(e) => { setTemplateSearch(e.target.value); setShowTemplates(true) }}
                  onFocus={() => templateSearch && setShowTemplates(true)}
                  className="pl-9"
                />
              </div>
              {showTemplates && templateSearch.length > 0 && (
                <div className="absolute z-50 mt-1 w-full rounded-md border bg-popover shadow-lg max-h-48 overflow-auto">
                  {templates.length === 0 ? (
                    <div className="p-3 text-sm text-muted-foreground">No templates found</div>
                  ) : (
                    templates.map((t) => (
                      <button key={t.id} type="button" className="w-full text-left px-3 py-2 text-sm hover:bg-accent flex justify-between" onClick={() => addFromTemplate(t)}>
                        <span>{t.name}{t.itemCategory ? ` — ${t.itemCategory}` : ''}{t.size ? ` ${t.size}` : ''}</span>
                        <span className="text-muted-foreground">${t.defaultPrice}</span>
                      </button>
                    ))
                  )}
                </div>
              )}
            </div>

            {/* Manual line item add */}
            <div className="space-y-2">
              <div className="relative flex items-center gap-2">
                <div className="flex-1 border-t" />
                <span className="text-xs text-muted-foreground">or add manually</span>
                <div className="flex-1 border-t" />
              </div>
              <div className="grid grid-cols-12 gap-2 items-end">
                <div className="col-span-2">
                  <Label className="text-xs">Type</Label>
                  <Select value={manualType} onValueChange={setManualType}>
                    <SelectTrigger className="h-9"><SelectValue /></SelectTrigger>
                    <SelectContent>
                      <SelectItem value="labor">Labor</SelectItem>
                      <SelectItem value="part">Part</SelectItem>
                      <SelectItem value="flat_rate">Flat Rate</SelectItem>
                      <SelectItem value="misc">Misc</SelectItem>
                    </SelectContent>
                  </Select>
                </div>
                <div className="col-span-3">
                  <Label className="text-xs">Description</Label>
                  <Input className="h-9" value={manualDesc} onChange={(e) => setManualDesc(e.target.value)} placeholder="e.g. Ernie Ball strings" />
                </div>
                <div className="col-span-2">
                  <Label className="text-xs">Qty</Label>
                  <Input className="h-9" type="number" step="0.001" value={manualQty} onChange={(e) => setManualQty(e.target.value)} />
                </div>
                <div className="col-span-2">
                  <Label className="text-xs">Price</Label>
                  <Input className="h-9" type="number" step="0.01" value={manualPrice} onChange={(e) => setManualPrice(e.target.value)} />
                </div>
                <div className="col-span-2">
                  <Label className="text-xs">Cost</Label>
                  <Input className="h-9" type="number" step="0.01" value={manualCost} onChange={(e) => setManualCost(e.target.value)} placeholder="Internal" />
                </div>
                <div className="col-span-1">
                  <Button type="button" size="sm" className="h-9 w-full" onClick={addManualItem} disabled={!manualDesc.trim()}>
                    <Plus className="h-4 w-4" />
                  </Button>
                </div>
              </div>
            </div>

            {/* Line items table */}
            {lineItems.length > 0 && (
              <div className="rounded-md border">
                <Table>
                  <TableHeader>
                    <TableRow>
                      <TableHead>Type</TableHead>
                      <TableHead>Description</TableHead>
                      <TableHead className="text-right">Qty</TableHead>
                      <TableHead className="text-right">Price</TableHead>
                      <TableHead className="text-right">Total</TableHead>
                      <TableHead className="w-10"></TableHead>
                    </TableRow>
                  </TableHeader>
                  <TableBody>
                    {lineItems.map((item, i) => (
                      <TableRow key={i}>
                        <TableCell><Badge variant="outline">{item.itemType.replace('_', ' ')}</Badge></TableCell>
                        <TableCell>{item.description}</TableCell>
                        <TableCell className="text-right">{item.qty}</TableCell>
                        <TableCell className="text-right">${item.unitPrice.toFixed(2)}</TableCell>
                        <TableCell className="text-right font-medium">${item.totalPrice.toFixed(2)}</TableCell>
                        <TableCell>
                          <Button type="button" variant="ghost" size="sm" onClick={() => removeLineItem(i)}>
                            <Trash2 className="h-3 w-3 text-destructive" />
                          </Button>
                        </TableCell>
                      </TableRow>
                    ))}
                    <TableRow>
                      <TableCell colSpan={4} className="text-right font-semibold">Estimated Total</TableCell>
                      <TableCell className="text-right font-bold text-primary">${estimatedTotal.toFixed(2)}</TableCell>
                      <TableCell></TableCell>
                    </TableRow>
                  </TableBody>
                </Table>
              </div>
            )}
          </CardContent>
        </Card>

        {/* Photos Section */}
        <Card>
          <CardHeader><CardTitle className="text-lg">Intake Photos</CardTitle></CardHeader>
          <CardContent className="space-y-4">
            <p className="text-sm text-muted-foreground">Optional — document item condition at intake</p>
            <div className="flex flex-wrap gap-3">
              {photos.map((photo, i) => (
                <div key={i} className="relative group">
                  <img src={URL.createObjectURL(photo)} alt={`Intake photo ${i + 1}`} className="h-24 w-24 object-cover rounded-md border" />
                  <button type="button" className="absolute -top-2 -right-2 h-5 w-5 rounded-full bg-destructive text-destructive-foreground flex items-center justify-center opacity-0 group-hover:opacity-100 transition-opacity" onClick={() => removePhoto(i)}>
                    <X className="h-3 w-3" />
                  </button>
                </div>
              ))}
              <button type="button" className="h-24 w-24 rounded-md border-2 border-dashed border-muted-foreground/30 flex flex-col items-center justify-center text-muted-foreground hover:border-primary hover:text-primary transition-colors" onClick={() => photoInputRef.current?.click()}>
                <ImageIcon className="h-6 w-6 mb-1" />
                <span className="text-xs">Add Photo</span>
              </button>
            </div>
            <input ref={photoInputRef} type="file" accept="image/jpeg,image/png,image/webp" multiple className="hidden" onChange={addPhotos} />
          </CardContent>
        </Card>

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