import { useState } from 'react'
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query'
import {
  repairTicketDetailOptions, repairTicketKeys, repairTicketMutations,
  repairLineItemListOptions,
} from '@/api/repairs'
import { api } from '@/lib/api-client'
import { StatusProgress } from '@/components/repairs/status-progress'
import { TicketNotes } from '@/components/repairs/ticket-notes'
import { TicketPhotos } from '@/components/repairs/ticket-photos'
import { Button } from '@/components/ui/button'
import { Badge } from '@/components/ui/badge'
import { Separator } from '@/components/ui/separator'
import { Mail, ChevronRight, Wrench } from 'lucide-react'
import { toast } from 'sonner'

const STATUS_FLOW = ['new', 'intake', 'diagnosing', 'pending_approval', 'approved', 'in_progress', 'ready', 'picked_up']

interface RepairDetailPanelProps {
  ticketId: string | null
  canEdit: boolean
}

export function RepairDetailPanel({ ticketId, canEdit }: RepairDetailPanelProps) {
  const queryClient = useQueryClient()
  const [activeSection, setActiveSection] = useState<'details' | 'notes' | 'photos'>('details')

  const { data: ticket, isLoading } = useQuery({
    ...repairTicketDetailOptions(ticketId ?? ''),
    enabled: !!ticketId,
  })

  const { data: lineItemsData } = useQuery({
    ...repairLineItemListOptions(ticketId ?? '', { page: 1, limit: 100, q: undefined, sort: undefined, order: 'asc' }),
    enabled: !!ticketId,
  })

  const statusMutation = useMutation({
    mutationFn: (status: string) => repairTicketMutations.updateStatus(ticketId!, status),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: repairTicketKeys.detail(ticketId!) })
      queryClient.invalidateQueries({ queryKey: ['repair-tickets', 'station-all'] })
      toast.success('Status updated')
    },
    onError: (err) => toast.error(err.message),
  })

  const emailEstimateMutation = useMutation({
    mutationFn: (email: string) => api.post(`/v1/repair-tickets/${ticketId}/email-estimate`, { email }),
    onSuccess: () => toast.success('Estimate emailed'),
    onError: (err) => toast.error(err.message),
  })

  if (!ticketId) {
    return (
      <div className="flex items-center justify-center h-full text-muted-foreground">
        <div className="text-center space-y-2">
          <Wrench className="h-10 w-10 mx-auto opacity-20" />
          <p className="text-sm">Select a ticket from the queue</p>
        </div>
      </div>
    )
  }

  if (isLoading || !ticket) {
    return (
      <div className="p-4 space-y-4">
        <div className="h-8 bg-muted animate-pulse rounded" />
        <div className="h-20 bg-muted animate-pulse rounded" />
        <div className="h-40 bg-muted animate-pulse rounded" />
      </div>
    )
  }

  const lineItems = lineItemsData?.data ?? []
  const currentIdx = STATUS_FLOW.indexOf(ticket.status)
  const nextStatus = currentIdx >= 0 && currentIdx < STATUS_FLOW.length - 1 ? STATUS_FLOW[currentIdx + 1] : null
  const isTerminal = ['picked_up', 'delivered', 'cancelled'].includes(ticket.status)

  function handleStatusClick(status: string) {
    if (canEdit && !isTerminal) statusMutation.mutate(status)
  }

  function handleEmailEstimate() {
    const email = (ticket as any).customerEmail
    if (email) {
      emailEstimateMutation.mutate(email)
    } else {
      toast.error('No customer email on file')
    }
  }

  return (
    <div className="flex flex-col h-full overflow-hidden">
      {/* Header */}
      <div className="p-3 border-b border-border shrink-0">
        <div className="flex items-center justify-between mb-2">
          <div>
            <h3 className="text-lg font-semibold">#{ticket.ticketNumber}</h3>
            <p className="text-sm text-muted-foreground">{ticket.customerName}</p>
          </div>
          <div className="flex gap-2">
            <Button variant="outline" size="sm" className="gap-1.5" onClick={handleEmailEstimate}>
              <Mail className="h-3.5 w-3.5" />
              <span className="hidden lg:inline">Email Estimate</span>
            </Button>
            {canEdit && nextStatus && !isTerminal && (
              <Button size="sm" className="gap-1.5" onClick={() => statusMutation.mutate(nextStatus)}>
                Next <ChevronRight className="h-3.5 w-3.5" />
              </Button>
            )}
          </div>
        </div>

        <StatusProgress
          currentStatus={ticket.status}
          onStatusClick={canEdit && !isTerminal ? handleStatusClick : undefined}
        />
      </div>

      {/* Section toggle */}
      <div className="flex gap-1 px-3 py-2 border-b border-border shrink-0 bg-muted/30">
        {(['details', 'notes', 'photos'] as const).map((s) => (
          <Button
            key={s}
            variant={activeSection === s ? 'default' : 'ghost'}
            size="sm"
            className="h-7 text-xs capitalize"
            onClick={() => setActiveSection(s)}
          >
            {s}
          </Button>
        ))}
      </div>

      {/* Content */}
      <div className="flex-1 overflow-y-auto p-3">
        {activeSection === 'details' && (
          <div className="space-y-4">
            {/* Item info */}
            <div className="space-y-1">
              <p className="text-sm"><span className="text-muted-foreground">Item:</span> {ticket.itemDescription ?? 'N/A'}</p>
              {ticket.serialNumber && <p className="text-sm"><span className="text-muted-foreground">S/N:</span> {ticket.serialNumber}</p>}
              {ticket.conditionIn && <p className="text-sm"><span className="text-muted-foreground">Condition:</span> {ticket.conditionIn}</p>}
              {ticket.conditionInNotes && <p className="text-sm text-muted-foreground">{ticket.conditionInNotes}</p>}
            </div>

            <Separator />

            {/* Problem */}
            <div>
              <p className="text-xs font-medium text-muted-foreground mb-1">Problem</p>
              <p className="text-sm">{ticket.problemDescription}</p>
            </div>

            {/* Dates */}
            <div className="flex gap-4">
              {ticket.promisedDate && (
                <div>
                  <p className="text-xs text-muted-foreground">Promised</p>
                  <p className="text-sm font-medium">{new Date(ticket.promisedDate).toLocaleDateString()}</p>
                </div>
              )}
              {ticket.estimatedCost && (
                <div>
                  <p className="text-xs text-muted-foreground">Estimate</p>
                  <p className="text-sm font-medium">${ticket.estimatedCost}</p>
                </div>
              )}
              {ticket.actualCost && (
                <div>
                  <p className="text-xs text-muted-foreground">Actual</p>
                  <p className="text-sm font-medium">${ticket.actualCost}</p>
                </div>
              )}
            </div>

            {/* Line items */}
            {lineItems.length > 0 && (
              <>
                <Separator />
                <div>
                  <p className="text-xs font-medium text-muted-foreground mb-2">Line Items</p>
                  <div className="space-y-1">
                    {lineItems.map((item) => (
                      <div key={item.id} className="flex items-center justify-between text-sm py-1">
                        <div className="flex items-center gap-2">
                          <Badge variant="outline" className="text-[10px] h-5">{item.itemType}</Badge>
                          <span>{item.description}</span>
                        </div>
                        <span className="font-medium">${item.totalPrice}</span>
                      </div>
                    ))}
                    <Separator />
                    <div className="flex justify-between text-sm font-semibold pt-1">
                      <span>Total</span>
                      <span>${lineItems.reduce((sum, i) => sum + parseFloat(i.totalPrice), 0).toFixed(2)}</span>
                    </div>
                  </div>
                </div>
              </>
            )}
          </div>
        )}

        {activeSection === 'notes' && ticketId && (
          <TicketNotes ticketId={ticketId} />
        )}

        {activeSection === 'photos' && ticketId && (
          <TicketPhotos ticketId={ticketId} currentStatus={ticket.status} />
        )}
      </div>
    </div>
  )
}
