'use client';

import { useState } from 'react';
import { useQuery } from '@tanstack/react-query';
import { Card, CardContent } from '@/components/ui/card';
import { Input } from '@/components/ui/input';
import { Button } from '@/components/ui/button';
import { Skeleton } from '@/components/ui/skeleton';
import {
  Table, TableBody, TableCell, TableHead, TableHeader, TableRow,
} from '@/components/ui/table';
import { Search, Plus } from 'lucide-react';
import { api } from '@/lib/api';
import { useDebounce } from '@/lib/hooks';
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 STATUS_COLORS: Record<string, string> = {
  OPEN: 'bg-blue-100 text-blue-700',
  IN_PROGRESS: 'bg-yellow-100 text-yellow-700',
  RESOLVED: 'bg-emerald-100 text-emerald-700',
  CLOSED: 'bg-gray-100 text-gray-500',
};
const TYPE_COLORS: Record<string, string> = {
  INSTALLATION: 'bg-purple-100 text-purple-700',
  SUPPORT: 'bg-orange-100 text-orange-700',
  BILLING: 'bg-cyan-100 text-cyan-700',
};
const PRIORITY_COLORS: Record<string, string> = {
  NORMAL: 'bg-gray-100 text-gray-600',
  HIGH: 'bg-red-100 text-red-700',
};

const STATUSES = ['', 'OPEN', 'IN_PROGRESS', 'RESOLVED', 'CLOSED'];
const TYPES = ['', 'INSTALLATION', 'SUPPORT', 'BILLING'];

export default function TicketsPage() {
  const [search, setSearch] = useState('');
  const [status, setStatus] = useState('');
  const [type, setType] = useState('');
  const [page, setPage] = useState(1);
  const debouncedSearch = useDebounce(search, 400);
  const limit = 20;

  const { data, isLoading } = useQuery({
    queryKey: ['tickets', debouncedSearch, status, type, page],
    queryFn: async () => {
      const params = new URLSearchParams({ page: String(page), limit: String(limit) });
      if (status) params.set('status', status);
      if (type) params.set('type', type);
      if (debouncedSearch) params.set('search', debouncedSearch);
      const res = await api.get(`/api/v1/tickets?${params}`);
      return res.data;
    },
  });

  const tickets: Ticket[] = Array.isArray(data) ? data : (data?.data ?? data?.items ?? []);
  const total = (data as any)?.meta?.total ?? (data as any)?.total ?? tickets.length;

  return (
    <div>
      <div className="mb-6 flex items-center justify-between">
        <div>
          <h1 className="text-2xl font-bold text-slate-800">Tickets</h1>
          <p className="text-slate-500 text-sm mt-1">Support, installation, and billing issues</p>
        </div>
        <Button style={{ backgroundColor: '#0891B2', color: 'white' }}>
          <Plus size={16} className="mr-2" />New Ticket
        </Button>
      </div>

      {/* Filters */}
      <div className="mb-4 flex flex-wrap gap-3">
        <div className="relative flex-1 min-w-[200px] max-w-sm">
          <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>
        <div className="flex gap-1 flex-wrap">
          {STATUSES.map(s => (
            <button key={s} onClick={() => { setStatus(s); setPage(1); }}
              className={`px-3 py-1.5 rounded-lg text-xs font-medium border transition-colors ${
                status === s ? 'bg-cyan-600 text-white border-cyan-600' : 'bg-white text-slate-600 border-slate-200 hover:border-slate-300'
              }`}>{s || 'All Status'}</button>
          ))}
        </div>
        <div className="flex gap-1 flex-wrap">
          {TYPES.map(t => (
            <button key={t} onClick={() => { setType(t); setPage(1); }}
              className={`px-3 py-1.5 rounded-lg text-xs font-medium border transition-colors ${
                type === t ? 'bg-slate-700 text-white border-slate-700' : 'bg-white text-slate-600 border-slate-200 hover:border-slate-300'
              }`}>{t || 'All Type'}</button>
          ))}
        </div>
      </div>

      <Card>
        <CardContent className="p-0">
          <Table>
            <TableHeader>
              <TableRow>
                <TableHead>Subject</TableHead>
                <TableHead>Type</TableHead>
                <TableHead>Status</TableHead>
                <TableHead>Priority</TableHead>
                <TableHead>Client</TableHead>
                <TableHead>Assigned To</TableHead>
                <TableHead>Created</TableHead>
              </TableRow>
            </TableHeader>
            <TableBody>
              {isLoading ? (
                Array.from({ length: 8 }).map((_, i) => (
                  <TableRow key={i}>{Array.from({ length: 7 }).map((_, j) => (
                    <TableCell key={j}><Skeleton className="h-4 w-full" /></TableCell>
                  ))}</TableRow>
                ))
              ) : tickets.length === 0 ? (
                <TableRow><TableCell colSpan={7} className="text-center py-12 text-slate-400">No tickets found</TableCell></TableRow>
              ) : (
                tickets.map((t) => (
                  <TableRow key={t.id} className="hover:bg-slate-50">
                    <TableCell className="font-medium max-w-[200px] truncate">{t.subject}</TableCell>
                    <TableCell>
                      <span className={`inline-flex px-2 py-0.5 rounded-full text-xs font-medium ${TYPE_COLORS[t.type] ?? 'bg-gray-100 text-gray-600'}`}>
                        {t.type}
                      </span>
                    </TableCell>
                    <TableCell>
                      <span className={`inline-flex px-2 py-0.5 rounded-full text-xs font-medium ${STATUS_COLORS[t.status] ?? 'bg-gray-100 text-gray-600'}`}>
                        {t.status.replace('_', ' ')}
                      </span>
                    </TableCell>
                    <TableCell>
                      <span className={`inline-flex px-2 py-0.5 rounded-full text-xs font-medium ${PRIORITY_COLORS[t.priority] ?? 'bg-gray-100'}`}>
                        {t.priority}
                      </span>
                    </TableCell>
                    <TableCell className="text-sm">
                      {t.client ? `${t.client.firstName} ${t.client.lastName}` : '—'}
                    </TableCell>
                    <TableCell className="text-sm text-slate-500">
                      {t.assignedTo ? `${t.assignedTo.firstName} ${t.assignedTo.lastName}` : 'Unassigned'}
                    </TableCell>
                    <TableCell className="text-xs text-slate-400">
                      {format(new Date(t.createdAt), 'MMM d, yyyy')}
                    </TableCell>
                  </TableRow>
                ))
              )}
            </TableBody>
          </Table>
        </CardContent>
      </Card>
    </div>
  );
}
