'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 { 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 { format } from 'date-fns';

interface Payment {
  id: string;
  amount: number;
  channel: string;
  paymentDate: string;
  notes?: string;
  client?: { firstName: string; lastName: string; accountNumber: string };
  invoice?: { invoiceNumber: string };
  recordedBy?: { firstName: string; lastName: string };
}

const CHANNEL_COLORS: Record<string, string> = {
  CASH: 'bg-emerald-100 text-emerald-700',
  GCASH: 'bg-blue-100 text-blue-700',
  MAYA: 'bg-green-100 text-green-700',
  BANK_TRANSFER: 'bg-purple-100 text-purple-700',
  CHECK: 'bg-orange-100 text-orange-700',
};

export default function PaymentsPage() {
  const [page, setPage] = useState(1);
  const limit = 20;

  const { data, isLoading } = useQuery({
    queryKey: ['payments', page],
    queryFn: async () => {
      const res = await api.get(`/api/v1/payments?page=${page}&limit=${limit}`);
      return res.data;
    },
  });

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

  const totalAmount = payments.reduce((sum, p) => sum + Number(p.amount), 0);

  return (
    <div>
      <div className="mb-6 flex items-center justify-between">
        <div>
          <h1 className="text-2xl font-bold text-slate-800">Payments</h1>
          <p className="text-slate-500 text-sm mt-1">Payment collection records</p>
        </div>
        {payments.length > 0 && (
          <div className="bg-emerald-50 border border-emerald-200 rounded-lg px-4 py-2 text-right">
            <p className="text-xs text-emerald-600">Total (this page)</p>
            <p className="text-lg font-bold text-emerald-700">₱{totalAmount.toLocaleString()}</p>
          </div>
        )}
      </div>

      <Card>
        <CardContent className="p-0">
          <Table>
            <TableHeader>
              <TableRow>
                <TableHead>Date</TableHead>
                <TableHead>Client</TableHead>
                <TableHead>Invoice</TableHead>
                <TableHead>Channel</TableHead>
                <TableHead className="text-right">Amount</TableHead>
                <TableHead>Recorded By</TableHead>
                <TableHead>Notes</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>
                ))
              ) : payments.length === 0 ? (
                <TableRow>
                  <TableCell colSpan={7} className="text-center py-12 text-slate-400">No payments yet</TableCell>
                </TableRow>
              ) : (
                payments.map((p) => (
                  <TableRow key={p.id} className="hover:bg-slate-50">
                    <TableCell className="text-sm text-slate-500">
                      {format(new Date(p.paymentDate), 'MMM d, yyyy')}
                    </TableCell>
                    <TableCell className="text-sm">
                      {p.client ? `${p.client.firstName} ${p.client.lastName}` : '—'}
                    </TableCell>
                    <TableCell className="font-mono text-xs text-slate-500">
                      {p.invoice?.invoiceNumber ?? '—'}
                    </TableCell>
                    <TableCell>
                      <span className={`inline-flex items-center px-2 py-0.5 rounded-full text-xs font-medium ${CHANNEL_COLORS[p.channel] ?? 'bg-gray-100 text-gray-600'}`}>
                        {p.channel}
                      </span>
                    </TableCell>
                    <TableCell className="text-right font-semibold text-emerald-700">
                      ₱{Number(p.amount).toLocaleString()}
                    </TableCell>
                    <TableCell className="text-sm text-slate-500">
                      {p.recordedBy ? `${p.recordedBy.firstName} ${p.recordedBy.lastName}` : '—'}
                    </TableCell>
                    <TableCell className="text-xs text-slate-400 max-w-[150px] truncate">
                      {p.notes ?? '—'}
                    </TableCell>
                  </TableRow>
                ))
              )}
            </TableBody>
          </Table>
        </CardContent>
      </Card>

      {total > limit && (
        <div className="mt-4 flex items-center justify-between text-sm text-slate-500">
          <span>Page {page} of {Math.ceil(total / limit)}</span>
          <div className="flex gap-2">
            <button className="px-3 py-1 rounded border text-sm hover:bg-slate-50 disabled:opacity-40"
              onClick={() => setPage(p => Math.max(1, p - 1))} disabled={page === 1}>Previous</button>
            <button className="px-3 py-1 rounded border text-sm hover:bg-slate-50 disabled:opacity-40"
              onClick={() => setPage(p => p + 1)} disabled={page * limit >= total}>Next</button>
          </div>
        </div>
      )}
    </div>
  );
}
