'use client';

import { useState } from 'react';
import { useQuery } from '@tanstack/react-query';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Card, CardContent } from '@/components/ui/card';
import { Skeleton } from '@/components/ui/skeleton';
import {
  Table, TableBody, TableCell, TableHead, TableHeader, TableRow,
} from '@/components/ui/table';
import { Search } from 'lucide-react';
import { api } from '@/lib/api';
import { useDebounce } from '@/lib/hooks';
import { format } from 'date-fns';

interface Invoice {
  id: string;
  invoiceNumber: string;
  status: string;
  subtotal: number;
  lateFee: number;
  total: number;
  amountPaid: number;
  balance: number;
  dueDate: string;
  createdAt: string;
  client?: { firstName: string; lastName: string; accountNumber: string };
}

const STATUS_COLORS: Record<string, string> = {
  DRAFT: 'bg-gray-100 text-gray-600',
  SENT: 'bg-blue-100 text-blue-700',
  PARTIAL: 'bg-yellow-100 text-yellow-700',
  PAID: 'bg-emerald-100 text-emerald-700',
  OVERDUE: 'bg-red-100 text-red-700',
  VOID: 'bg-gray-100 text-gray-400',
};

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

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

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

  const STATUSES = ['', 'SENT', 'PARTIAL', 'PAID', 'OVERDUE', 'DRAFT', 'VOID'];

  return (
    <div>
      <div className="mb-6">
        <h1 className="text-2xl font-bold text-slate-800">Invoices</h1>
        <p className="text-slate-500 text-sm mt-1">Track billing and payment status</p>
      </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 by invoice # or client..." className="pl-9" value={search}
            onChange={(e) => { setSearch(e.target.value); setPage(1); }} />
        </div>
        <div className="flex gap-1">
          {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'}
            </button>
          ))}
        </div>
      </div>

      <Card>
        <CardContent className="p-0">
          <Table>
            <TableHeader>
              <TableRow>
                <TableHead>Invoice #</TableHead>
                <TableHead>Client</TableHead>
                <TableHead>Status</TableHead>
                <TableHead className="text-right">Total</TableHead>
                <TableHead className="text-right">Balance</TableHead>
                <TableHead>Due Date</TableHead>
              </TableRow>
            </TableHeader>
            <TableBody>
              {isLoading ? (
                Array.from({ length: 8 }).map((_, i) => (
                  <TableRow key={i}>
                    {Array.from({ length: 6 }).map((_, j) => (
                      <TableCell key={j}><Skeleton className="h-4 w-full" /></TableCell>
                    ))}
                  </TableRow>
                ))
              ) : invoices.length === 0 ? (
                <TableRow>
                  <TableCell colSpan={6} className="text-center py-12 text-slate-400">
                    No invoices found
                  </TableCell>
                </TableRow>
              ) : (
                invoices.map((inv) => (
                  <TableRow key={inv.id} className="hover:bg-slate-50">
                    <TableCell className="font-mono text-sm">{inv.invoiceNumber}</TableCell>
                    <TableCell className="text-sm">
                      {inv.client ? `${inv.client.firstName} ${inv.client.lastName}` : '—'}
                      {inv.client && <span className="text-xs text-slate-400 ml-1">#{inv.client.accountNumber}</span>}
                    </TableCell>
                    <TableCell>
                      <span className={`inline-flex items-center px-2 py-0.5 rounded-full text-xs font-medium ${STATUS_COLORS[inv.status] ?? 'bg-gray-100 text-gray-600'}`}>
                        {inv.status}
                      </span>
                    </TableCell>
                    <TableCell className="text-right font-medium">₱{Number(inv.total).toLocaleString()}</TableCell>
                    <TableCell className={`text-right text-sm ${Number(inv.balance) > 0 ? 'text-red-600 font-medium' : 'text-slate-400'}`}>
                      {Number(inv.balance) > 0 ? `₱${Number(inv.balance).toLocaleString()}` : '—'}
                    </TableCell>
                    <TableCell className={`text-sm ${new Date(inv.dueDate) < new Date() && inv.status !== 'PAID' && inv.status !== 'VOID' ? 'text-red-500' : 'text-slate-500'}`}>
                      {format(new Date(inv.dueDate), 'MMM d, yyyy')}
                    </TableCell>
                  </TableRow>
                ))
              )}
            </TableBody>
          </Table>
        </CardContent>
      </Card>
    </div>
  );
}
