import { useQuery } from '@tanstack/react-query'
import { api } from '@/lib/api-client'
import type { RepairTicket } from '@/types/repair'
import type { PaginatedResponse } from '@lunarfront/shared/schemas'
import { Input } from '@/components/ui/input'
import { Button } from '@/components/ui/button'
import { Badge } from '@/components/ui/badge'
import { Plus, Search } from 'lucide-react'
import { useState } from 'react'

const STATUS_COLORS: Record<string, string> = {
  new: 'bg-blue-500/10 text-blue-500',
  in_transit: 'bg-blue-500/10 text-blue-500',
  intake: 'bg-blue-500/10 text-blue-500',
  diagnosing: 'bg-yellow-500/10 text-yellow-500',
  pending_approval: 'bg-yellow-500/10 text-yellow-500',
  approved: 'bg-orange-500/10 text-orange-500',
  in_progress: 'bg-orange-500/10 text-orange-500',
  pending_parts: 'bg-orange-500/10 text-orange-500',
  ready: 'bg-green-500/10 text-green-500',
  picked_up: 'bg-muted text-muted-foreground',
  delivered: 'bg-muted text-muted-foreground',
  cancelled: 'bg-destructive/10 text-destructive',
}

const STATUS_LABELS: Record<string, string> = {
  new: 'New',
  in_transit: 'In Transit',
  intake: 'Intake',
  diagnosing: 'Diagnosing',
  pending_approval: 'Pending Approval',
  approved: 'Approved',
  in_progress: 'In Progress',
  pending_parts: 'Pending Parts',
  ready: 'Ready',
  picked_up: 'Picked Up',
  delivered: 'Delivered',
  cancelled: 'Cancelled',
}

interface RepairQueuePanelProps {
  selectedTicketId: string | null
  onSelectTicket: (id: string) => void
  onNewIntake: () => void
  statusFilter: string[] | null
}

export function RepairQueuePanel({ selectedTicketId, onSelectTicket, onNewIntake, statusFilter }: RepairQueuePanelProps) {
  const [search, setSearch] = useState('')

  const { data, isLoading } = useQuery({
    queryKey: ['repair-tickets', 'station-queue', search, statusFilter],
    queryFn: () => api.get<PaginatedResponse<RepairTicket>>('/v1/repair-tickets', {
      page: 1,
      limit: 100,
      q: search || undefined,
      sort: 'created_at',
      order: 'desc',
      ...(statusFilter ? { status: statusFilter.join(',') } : {}),
    }),
    staleTime: 30_000,
    refetchInterval: 30_000,
  })

  const tickets = data?.data ?? []

  function timeAgo(dateStr: string) {
    const diff = Date.now() - new Date(dateStr).getTime()
    const hours = Math.floor(diff / 3600000)
    if (hours < 1) return 'Just now'
    if (hours < 24) return `${hours}h ago`
    const days = Math.floor(hours / 24)
    return `${days}d ago`
  }

  return (
    <div className="flex flex-col h-full">
      <div className="p-3 space-y-2 shrink-0">
        <Button className="w-full h-11 gap-2" onClick={onNewIntake}>
          <Plus className="h-4 w-4" />
          New Intake
        </Button>
        <div className="relative">
          <Search className="absolute left-2.5 top-2.5 h-4 w-4 text-muted-foreground" />
          <Input
            placeholder="Search tickets..."
            value={search}
            onChange={(e) => setSearch(e.target.value)}
            className="pl-9 h-9"
          />
        </div>
      </div>

      <div className="flex-1 overflow-y-auto">
        {isLoading ? (
          <div className="p-3 space-y-2">
            {Array.from({ length: 5 }).map((_, i) => (
              <div key={i} className="h-16 bg-muted animate-pulse rounded-lg" />
            ))}
          </div>
        ) : tickets.length === 0 ? (
          <div className="p-6 text-center text-muted-foreground text-sm">
            No tickets found
          </div>
        ) : (
          <div className="px-2 pb-2 space-y-1">
            {tickets.map((ticket) => (
              <button
                key={ticket.id}
                className={`w-full text-left p-3 rounded-lg transition-colors ${
                  selectedTicketId === ticket.id
                    ? 'bg-primary/10 border border-primary/20'
                    : 'hover:bg-muted border border-transparent'
                }`}
                onClick={() => onSelectTicket(ticket.id)}
              >
                <div className="flex items-center justify-between mb-1">
                  <span className="text-sm font-medium">#{ticket.ticketNumber}</span>
                  <Badge variant="outline" className={`text-[10px] ${STATUS_COLORS[ticket.status] ?? ''}`}>
                    {STATUS_LABELS[ticket.status] ?? ticket.status}
                  </Badge>
                </div>
                <div className="text-sm text-foreground truncate">{ticket.customerName}</div>
                <div className="flex items-center justify-between mt-1">
                  <span className="text-xs text-muted-foreground truncate">{ticket.itemDescription ?? 'No item'}</span>
                  <span className="text-xs text-muted-foreground shrink-0 ml-2">{timeAgo(ticket.createdAt)}</span>
                </div>
              </button>
            ))}
          </div>
        )}
      </div>
    </div>
  )
}
