import { useState } from 'react'
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query'
import { api } from '@/lib/api-client'
import { repairTicketMutations, repairLineItemMutations, repairServiceTemplateListOptions } from '@/api/repairs'
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 { Separator } from '@/components/ui/separator'
import { Badge } from '@/components/ui/badge'
import { ArrowLeft, ArrowRight, Plus, Trash2, Check, Search } from 'lucide-react'
import { toast } from 'sonner'
import type { RepairServiceTemplate } from '@/types/repair'
import type { PaginatedResponse } from '@lunarfront/shared/schemas'

interface RepairIntakeFormProps {
  onComplete: (ticketId: string) => void
  onCancel: () => void
}

interface LineItemDraft {
  id: string
  itemType: string
  description: string
  qty: number
  unitPrice: number
}

const STEPS = ['Customer', 'Item', 'Problem & Estimate', 'Review']
const CONDITIONS = [
  { value: 'excellent', label: 'Excellent' },
  { value: 'good', label: 'Good' },
  { value: 'fair', label: 'Fair' },
  { value: 'poor', label: 'Poor' },
]

export function RepairIntakeForm({ onComplete, onCancel }: RepairIntakeFormProps) {
  const queryClient = useQueryClient()
  const [step, setStep] = useState(0)

  // Customer
  const [customerName, setCustomerName] = useState('')
  const [customerPhone, setCustomerPhone] = useState('')
  const [customerEmail, setCustomerEmail] = useState('')
  const [accountId, setAccountId] = useState<string | null>(null)

  // Account search
  const [accountSearch, setAccountSearch] = useState('')
  const { data: accountResults } = useQuery({
    queryKey: ['accounts', 'search', accountSearch],
    queryFn: () => api.get<PaginatedResponse<{ id: string; name: string; email: string | null; phone: string | null }>>('/v1/accounts', { page: 1, limit: 10, q: accountSearch }),
    enabled: accountSearch.length >= 2,
    staleTime: 10_000,
  })

  // Item
  const [itemDescription, setItemDescription] = useState('')
  const [serialNumber, setSerialNumber] = useState('')
  const [conditionIn, setConditionIn] = useState('')
  const [conditionInNotes, setConditionInNotes] = useState('')

  // Problem & Estimate
  const [problemDescription, setProblemDescription] = useState('')
  const [estimatedCost, setEstimatedCost] = useState('')
  const [promisedDate, setPromisedDate] = useState('')
  const [lineItems, setLineItems] = useState<LineItemDraft[]>([])

  // Templates for quick-add
  const { data: templatesData } = useQuery({
    ...repairServiceTemplateListOptions({ page: 1, limit: 100, q: undefined, sort: 'sort_order', order: 'asc' }),
  })
  const templates = templatesData?.data ?? []

  function addLineItem(template?: RepairServiceTemplate) {
    setLineItems([...lineItems, {
      id: crypto.randomUUID(),
      itemType: template?.itemType ?? 'labor',
      description: template?.description ?? template?.name ?? '',
      qty: 1,
      unitPrice: parseFloat(template?.defaultPrice ?? '0'),
    }])
  }

  function removeLineItem(id: string) {
    setLineItems(lineItems.filter(i => i.id !== id))
  }

  function updateLineItem(id: string, field: string, value: string | number) {
    setLineItems(lineItems.map(i => i.id === id ? { ...i, [field]: value } : i))
  }

  const lineItemTotal = lineItems.reduce((sum, i) => sum + i.qty * i.unitPrice, 0)

  const createMutation = useMutation({
    mutationFn: async () => {
      const ticket = await repairTicketMutations.create({
        customerName,
        customerPhone: customerPhone || undefined,
        accountId: accountId || undefined,
        itemDescription: itemDescription || undefined,
        serialNumber: serialNumber || undefined,
        conditionIn: conditionIn || undefined,
        conditionInNotes: conditionInNotes || undefined,
        problemDescription,
        estimatedCost: estimatedCost ? parseFloat(estimatedCost) : undefined,
        promisedDate: promisedDate || undefined,
      })

      // Create line items
      for (const item of lineItems) {
        await repairLineItemMutations.create(ticket.id, {
          itemType: item.itemType,
          description: item.description,
          qty: item.qty,
          unitPrice: item.unitPrice,
        })
      }

      return ticket
    },
    onSuccess: (ticket) => {
      queryClient.invalidateQueries({ queryKey: ['repair-tickets'] })
      toast.success(`Ticket #${ticket.ticketNumber} created`)
      onComplete(ticket.id)
    },
    onError: (err) => toast.error(err.message),
  })

  function selectAccount(acct: { id: string; name: string; email: string | null; phone: string | null }) {
    setAccountId(acct.id)
    setCustomerName(acct.name)
    if (acct.phone) setCustomerPhone(acct.phone)
    if (acct.email) setCustomerEmail(acct.email)
    setAccountSearch('')
  }

  function canProceed() {
    if (step === 0) return customerName.trim().length > 0
    if (step === 1) return true
    if (step === 2) return problemDescription.trim().length > 0
    return true
  }

  return (
    <div className="flex flex-col h-full">
      {/* Step indicator */}
      <div className="flex items-center gap-2 px-4 py-3 border-b border-border shrink-0">
        <Button variant="ghost" size="sm" onClick={onCancel}>
          <ArrowLeft className="h-4 w-4 mr-1" />Cancel
        </Button>
        <div className="flex-1" />
        <div className="flex items-center gap-1">
          {STEPS.map((s, i) => (
            <div key={s} className="flex items-center gap-1">
              <div className={`h-7 px-3 rounded-full text-xs flex items-center font-medium ${
                i === step ? 'bg-primary text-primary-foreground' :
                i < step ? 'bg-primary/20 text-primary' : 'bg-muted text-muted-foreground'
              }`}>
                {i < step ? <Check className="h-3 w-3" /> : i + 1}
                <span className="ml-1.5 hidden md:inline">{s}</span>
              </div>
              {i < STEPS.length - 1 && <div className="w-4 h-px bg-border" />}
            </div>
          ))}
        </div>
        <div className="flex-1" />
      </div>

      {/* Step content */}
      <div className="flex-1 overflow-y-auto p-4 max-w-2xl mx-auto w-full">
        {step === 0 && (
          <div className="space-y-4">
            <h3 className="text-lg font-semibold">Customer</h3>
            <div className="space-y-2">
              <Label>Search existing accounts</Label>
              <div className="relative">
                <Search className="absolute left-2.5 top-2.5 h-4 w-4 text-muted-foreground" />
                <Input
                  placeholder="Search by name..."
                  value={accountSearch}
                  onChange={(e) => setAccountSearch(e.target.value)}
                  className="pl-9"
                />
              </div>
              {accountSearch.length >= 2 && accountResults?.data && accountResults.data.length > 0 && (
                <div className="border rounded-md max-h-40 overflow-y-auto">
                  {accountResults.data.map((acct) => (
                    <button
                      key={acct.id}
                      className="w-full text-left px-3 py-2 text-sm hover:bg-muted transition-colors"
                      onClick={() => selectAccount(acct)}
                    >
                      <span className="font-medium">{acct.name}</span>
                      {acct.phone && <span className="text-muted-foreground ml-2">{acct.phone}</span>}
                    </button>
                  ))}
                </div>
              )}
            </div>
            <Separator />
            <p className="text-sm text-muted-foreground">Or enter walk-in customer info:</p>
            <div className="space-y-2">
              <Label>Name *</Label>
              <Input value={customerName} onChange={(e) => setCustomerName(e.target.value)} placeholder="Customer name" />
            </div>
            <div className="grid grid-cols-2 gap-4">
              <div className="space-y-2">
                <Label>Phone</Label>
                <Input value={customerPhone} onChange={(e) => setCustomerPhone(e.target.value)} placeholder="555-1234" />
              </div>
              <div className="space-y-2">
                <Label>Email</Label>
                <Input type="email" value={customerEmail} onChange={(e) => setCustomerEmail(e.target.value)} placeholder="email@example.com" />
              </div>
            </div>
          </div>
        )}

        {step === 1 && (
          <div className="space-y-4">
            <h3 className="text-lg font-semibold">Item Details</h3>
            <div className="space-y-2">
              <Label>Item Description</Label>
              <Input value={itemDescription} onChange={(e) => setItemDescription(e.target.value)} placeholder="e.g. Fender Stratocaster, iPhone 15, etc." />
            </div>
            <div className="grid grid-cols-2 gap-4">
              <div className="space-y-2">
                <Label>Serial Number</Label>
                <Input value={serialNumber} onChange={(e) => setSerialNumber(e.target.value)} placeholder="Optional" />
              </div>
              <div className="space-y-2">
                <Label>Condition</Label>
                <Select value={conditionIn} onValueChange={setConditionIn}>
                  <SelectTrigger><SelectValue placeholder="Select condition" /></SelectTrigger>
                  <SelectContent>
                    {CONDITIONS.map(c => <SelectItem key={c.value} value={c.value}>{c.label}</SelectItem>)}
                  </SelectContent>
                </Select>
              </div>
            </div>
            <div className="space-y-2">
              <Label>Condition Notes</Label>
              <Textarea value={conditionInNotes} onChange={(e) => setConditionInNotes(e.target.value)} placeholder="Describe any existing damage, scratches, etc." rows={3} />
            </div>
          </div>
        )}

        {step === 2 && (
          <div className="space-y-4">
            <h3 className="text-lg font-semibold">Problem & Estimate</h3>
            <div className="space-y-2">
              <Label>Problem Description *</Label>
              <Textarea value={problemDescription} onChange={(e) => setProblemDescription(e.target.value)} placeholder="Describe what needs to be repaired..." rows={3} />
            </div>
            <div className="grid grid-cols-2 gap-4">
              <div className="space-y-2">
                <Label>Estimated Cost</Label>
                <Input type="number" step="0.01" value={estimatedCost} onChange={(e) => setEstimatedCost(e.target.value)} placeholder="0.00" />
              </div>
              <div className="space-y-2">
                <Label>Promised Date</Label>
                <Input type="date" value={promisedDate} onChange={(e) => setPromisedDate(e.target.value)} />
              </div>
            </div>

            <Separator />

            <div className="flex items-center justify-between">
              <Label>Line Items</Label>
              <Button variant="outline" size="sm" onClick={() => addLineItem()}>
                <Plus className="h-3.5 w-3.5 mr-1" />Add Item
              </Button>
            </div>

            {/* Template quick-add */}
            {templates.length > 0 && (
              <div className="flex gap-1.5 flex-wrap">
                {templates.slice(0, 10).map(t => (
                  <Button key={t.id} variant="outline" size="sm" className="h-7 text-xs" onClick={() => addLineItem(t)}>
                    {t.name} — ${t.defaultPrice}
                  </Button>
                ))}
              </div>
            )}

            {lineItems.map((item) => (
              <div key={item.id} className="flex items-end gap-2">
                <div className="w-24 space-y-1">
                  <Label className="text-xs">Type</Label>
                  <Select value={item.itemType} onValueChange={(v) => updateLineItem(item.id, 'itemType', v)}>
                    <SelectTrigger className="h-8 text-xs"><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="flex-1 space-y-1">
                  <Label className="text-xs">Description</Label>
                  <Input className="h-8 text-sm" value={item.description} onChange={(e) => updateLineItem(item.id, 'description', e.target.value)} />
                </div>
                <div className="w-16 space-y-1">
                  <Label className="text-xs">Qty</Label>
                  <Input className="h-8 text-sm" type="number" min={1} value={item.qty} onChange={(e) => updateLineItem(item.id, 'qty', parseInt(e.target.value) || 1)} />
                </div>
                <div className="w-24 space-y-1">
                  <Label className="text-xs">Price</Label>
                  <Input className="h-8 text-sm" type="number" step="0.01" value={item.unitPrice} onChange={(e) => updateLineItem(item.id, 'unitPrice', parseFloat(e.target.value) || 0)} />
                </div>
                <Button variant="ghost" size="icon" className="h-8 w-8 shrink-0" onClick={() => removeLineItem(item.id)}>
                  <Trash2 className="h-3.5 w-3.5" />
                </Button>
              </div>
            ))}

            {lineItems.length > 0 && (
              <div className="text-right text-sm font-semibold">
                Line Item Total: ${lineItemTotal.toFixed(2)}
              </div>
            )}
          </div>
        )}

        {step === 3 && (
          <div className="space-y-4">
            <h3 className="text-lg font-semibold">Review</h3>
            <div className="space-y-3 text-sm">
              <div>
                <p className="text-muted-foreground text-xs">Customer</p>
                <p className="font-medium">{customerName}</p>
                {customerPhone && <p className="text-muted-foreground">{customerPhone}</p>}
              </div>
              {itemDescription && (
                <div>
                  <p className="text-muted-foreground text-xs">Item</p>
                  <p>{itemDescription}{serialNumber ? ` (S/N: ${serialNumber})` : ''}</p>
                  {conditionIn && <Badge variant="outline" className="text-xs mt-1">{conditionIn}</Badge>}
                </div>
              )}
              <div>
                <p className="text-muted-foreground text-xs">Problem</p>
                <p>{problemDescription}</p>
              </div>
              {(estimatedCost || promisedDate) && (
                <div className="flex gap-6">
                  {estimatedCost && <div><p className="text-muted-foreground text-xs">Estimate</p><p className="font-medium">${estimatedCost}</p></div>}
                  {promisedDate && <div><p className="text-muted-foreground text-xs">Promised</p><p>{new Date(promisedDate + 'T00:00:00').toLocaleDateString()}</p></div>}
                </div>
              )}
              {lineItems.length > 0 && (
                <div>
                  <p className="text-muted-foreground text-xs mb-1">Line Items</p>
                  {lineItems.map(i => (
                    <div key={i.id} className="flex justify-between py-0.5">
                      <span>{i.description} x{i.qty}</span>
                      <span className="font-medium">${(i.qty * i.unitPrice).toFixed(2)}</span>
                    </div>
                  ))}
                  <Separator className="my-1" />
                  <div className="flex justify-between font-semibold">
                    <span>Total</span>
                    <span>${lineItemTotal.toFixed(2)}</span>
                  </div>
                </div>
              )}
            </div>
          </div>
        )}
      </div>

      {/* Navigation */}
      <div className="flex items-center justify-between p-4 border-t border-border shrink-0">
        <Button variant="outline" onClick={() => step > 0 ? setStep(step - 1) : onCancel()}>
          <ArrowLeft className="h-4 w-4 mr-1" />
          {step === 0 ? 'Cancel' : 'Back'}
        </Button>
        {step < STEPS.length - 1 ? (
          <Button onClick={() => setStep(step + 1)} disabled={!canProceed()}>
            Next <ArrowRight className="h-4 w-4 ml-1" />
          </Button>
        ) : (
          <Button onClick={() => createMutation.mutate()} disabled={createMutation.isPending}>
            {createMutation.isPending ? 'Creating...' : 'Create Ticket'}
          </Button>
        )}
      </div>
    </div>
  )
}
