'use client';

import { useState } from 'react';
import { useQuery } from '@tanstack/react-query';
import { api } from '@/lib/api';
import { Card, CardContent } from '@/components/ui/card';
import { Input } from '@/components/ui/input';
import { Skeleton } from '@/components/ui/skeleton';
import { Search, Plus, ChevronRight } from 'lucide-react';
import { format } from 'date-fns';

interface Ticket {
  id: string;
  subject: string;
  type: string;
  status: string;
  priority: string;
  createdAt: string;
  client?: { firstName: string; lastName: string; accountNumber: string };
  assignedTo?: { firstName: string; lastName: string };
}

const statusColors: Record<string, string> = {
  OPEN: 'bg-blue-100 text-blue-700',
  IN_PROGRESS: 'bg-yellow-100 text-yellow-700',
  RESOLVED: 'bg-green-100 text-green-700',
  CLOSED: 'bg-gray-100 text-gray-500',
};

const priorityColors: Record<string, string> = {
  HIGH: 'bg-red-100 text-red-700',
  NORMAL: 'bg-slate-100 text-slate-600',
};

const typeColors: Record<string, string> = {
  INSTALLATION: 'bg-cyan-100 text-cyan-700',
  SUPPORT: 'bg-purple-100 text-purple-700',
  BILLING: 'bg-orange-100 text-orange-700',
};

export default function TicketsPage() {
  const [search, setSearch] = useState('');
  const [statusFilter, setStatusFilter] = useState('');
  const [typeFilter, setTypeFilter] = useState('');
  const [page, setPage] = useState(1);

  const { data, isLoading } = useQuery<{ data: Ticket[]; total: number }>({
    queryKey: ['tickets', search, statusFilter, typeFilter, page],
    queryFn: async () => {
      const params = new URLSearchParams({ page: String(page), limit: '20' });
      if (statusFilter) params.set('status', statusFilter);
      if (typeFilter) params.set('type', typeFilter);
      const res = await api.get(`/api/v1/tickets?${params}`);
      return res.data;
    },
    staleTime: 30_000,
  });

  const tickets = data?.data ?? [];
  const total = data?.total ?? 0;

  return (
    <div>
      <div className="flex items-center justify-between mb-6">
        <div>
          <h1 className="text-2xl font-bold text-slate-800">Tickets</h1>
          <p className="text-slate-500 text-sm mt-1">{total} tickets</p>
        </div>
        <button
          className="flex items-center gap-2 px-4 py-2 rounded-lg text-sm font-medium text-white"
          style={{ backgroundColor: '#0891B2' }}
        >
          <Plus size={16} />
          New Ticket
        </button>
      </div>

      <div className="flex gap-3 mb-4 flex-wrap">
        <div className="relative flex-1 min-w-[200px]">
          <Search size={16} className="absolute left-3 top-1/2 -translate-y-1/2 text-slate-400" />
          <Input placeholder="Search tickets..." className="pl-9" value={search}
            onChange={(e) => { setSearch(e.target.value); setPage(1); }} />
        </div>
        <select className="border rounded-md px-3 py-2 text-sm bg-white"
          value={typeFilter} onChange={(e) => { setTypeFilter(e.target.value); setPage(1); }}>
          <option value="">All Types</option>
          {['INSTALLATION', 'SUPPORT', 'BILLING'].map(t => (
            <option key={t} value={t}>{t}</option>
          ))}
        </select>
        <select className="border rounded-md px-3 py-2 text-sm bg-white"
          value={statusFilter} onChange={(e) => { setStatusFilter(e.target.value); setPage(1); }}>
          <option value="">All Statuses</option>
          {['OPEN', 'IN_PROGRESS', 'RESOLVED', 'CLOSED'].map(s => (
            <option key={s} value={s}>{s.replace('_', ' ')}</option>
          ))}
        </select>
      </div>

      <Card className="border shadow-sm">
        <CardContent className="p-0">
          <div className="overflow-x-auto">
            <table className="w-full text-sm">
              <thead>
                <tr className="border-b bg-slate-50">
                  <th className="text-left px-4 py-3 font-medium text-slate-500">Subject</th>
                  <th className="text-left px-4 py-3 font-medium text-slate-500 hidden md:table-cell">Client</th>
                  <th className="text-left px-4 py-3 font-medium text-slate-500">Type</th>
                  <th className="text-left px-4 py-3 font-medium text-slate-500">Priority</th>
                  <th className="text-left px-4 py-3 font-medium text-slate-500">Status</th>
                  <th className="text-left px-4 py-3 font-medium text-slate-500 hidden lg:table-cell">Assigned</th>
                  <th className="text-left px-4 py-3 font-medium text-slate-500 hidden xl:table-cell">Created</th>
                  <th className="px-4 py-3"></th>
                </tr>
              </thead>
              <tbody>
                {isLoading
                  ? Array.from({ length: 8 }).map((_, i) => (
                      <tr key={i} className="border-b">
                        {Array.from({ length: 8 }).map((_, j) => (
                          <td key={j} className="px-4 py-3"><Skeleton className="h-4 w-16" /></td>
                        ))}
                      </tr>
                    ))
                  : tickets.map((t) => (
                      <tr key={t.id} className="border-b hover:bg-slate-50 cursor-pointer transition-colors">
                        <td className="px-4 py-3 text-slate-800 font-medium max-w-[200px] truncate">
                          {t.subject}
                        </td>
                        <td className="px-4 py-3 text-slate-600 hidden md:table-cell">
                          {t.client ? `${t.client.firstName} ${t.client.lastName}` : '—'}
                          <div className="text-xs text-slate-400">{t.client?.accountNumber}</div>
                        </td>
                        <td className="px-4 py-3">
                          <span className={`px-2 py-0.5 rounded-full text-xs font-medium ${typeColors[t.type] ?? 'bg-gray-100 text-gray-500'}`}>
                            {t.type}
                          </span>
                        </td>
                        <td className="px-4 py-3">
                          <span className={`px-2 py-0.5 rounded-full text-xs font-medium ${priorityColors[t.priority] ?? 'bg-gray-100 text-gray-500'}`}>
                            {t.priority}
                          </span>
                        </td>
                        <td className="px-4 py-3">
                          <span className={`px-2 py-0.5 rounded-full text-xs font-medium ${statusColors[t.status] ?? 'bg-gray-100 text-gray-500'}`}>
                            {t.status?.replace('_', ' ')}
                          </span>
                        </td>
                        <td className="px-4 py-3 text-slate-600 hidden lg:table-cell">
                          {t.assignedTo ? `${t.assignedTo.firstName} ${t.assignedTo.lastName}` : 'Unassigned'}
                        </td>
                        <td className="px-4 py-3 text-slate-500 hidden xl:table-cell">
                          {t.createdAt ? format(new Date(t.createdAt), 'MMM d') : '—'}
                        </td>
                        <td className="px-4 py-3 text-slate-400"><ChevronRight size={16} /></td>
                      </tr>
                    ))}
              </tbody>
            </table>
          </div>
          {!isLoading && tickets.length === 0 && (
            <div className="text-center py-12 text-slate-400">No tickets found</div>
          )}
        </CardContent>
      </Card>
    </div>
  );
}
