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

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

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

const peso = (v: string | number) =>
  '₱' + Number(v ?? 0).toLocaleString('en-PH', { minimumFractionDigits: 2 });

export default function PaymentsPage() {
  const [search, setSearch] = useState('');
  const [channelFilter, setChannelFilter] = useState('');
  const [page, setPage] = useState(1);

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

  const payments = 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">Payments</h1>
          <p className="text-slate-500 text-sm mt-1">{total} payments</p>
        </div>
      </div>

      <div className="flex gap-3 mb-4">
        <div className="relative flex-1">
          <Search size={16} className="absolute left-3 top-1/2 -translate-y-1/2 text-slate-400" />
          <Input placeholder="Search..." 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 text-slate-700 bg-white"
          value={channelFilter}
          onChange={(e) => { setChannelFilter(e.target.value); setPage(1); }}
        >
          <option value="">All Channels</option>
          {['CASH', 'GCASH', 'MAYA', 'BANK_TRANSFER', 'CHECK'].map((c) => (
            <option key={c} value={c}>{c.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">Date</th>
                  <th className="text-left px-4 py-3 font-medium text-slate-500 hidden md:table-cell">Client</th>
                  <th className="text-right px-4 py-3 font-medium text-slate-500">Amount</th>
                  <th className="text-left px-4 py-3 font-medium text-slate-500">Channel</th>
                  <th className="text-left px-4 py-3 font-medium text-slate-500 hidden lg:table-cell">Recorded By</th>
                  <th className="text-left px-4 py-3 font-medium text-slate-500 hidden xl:table-cell">Invoice</th>
                </tr>
              </thead>
              <tbody>
                {isLoading
                  ? Array.from({ length: 8 }).map((_, i) => (
                      <tr key={i} className="border-b">
                        {Array.from({ length: 6 }).map((_, j) => (
                          <td key={j} className="px-4 py-3"><Skeleton className="h-4 w-20" /></td>
                        ))}
                      </tr>
                    ))
                  : payments.map((p) => (
                      <tr key={p.id} className="border-b hover:bg-slate-50 transition-colors">
                        <td className="px-4 py-3 text-slate-600">
                          {p.paymentDate ? format(new Date(p.paymentDate), 'MMM d, yyyy') : '—'}
                        </td>
                        <td className="px-4 py-3 text-slate-700 hidden md:table-cell">
                          {p.client ? `${p.client.firstName} ${p.client.lastName}` : '—'}
                          <div className="text-xs text-slate-400">{p.client?.accountNumber}</div>
                        </td>
                        <td className="px-4 py-3 text-right font-semibold text-slate-800">{peso(p.amount)}</td>
                        <td className="px-4 py-3">
                          <span className={`px-2 py-0.5 rounded-full text-xs font-medium ${channelColors[p.channel] ?? 'bg-gray-100 text-gray-500'}`}>
                            {p.channel?.replace('_', ' ')}
                          </span>
                        </td>
                        <td className="px-4 py-3 text-slate-600 hidden lg:table-cell">
                          {p.recordedBy ? `${p.recordedBy.firstName} ${p.recordedBy.lastName}` : '—'}
                        </td>
                        <td className="px-4 py-3 text-slate-500 font-mono text-xs hidden xl:table-cell">
                          {p.invoice?.invoiceNumber ?? '—'}
                        </td>
                      </tr>
                    ))}
              </tbody>
            </table>
          </div>
          {!isLoading && payments.length === 0 && (
            <div className="text-center py-12 text-slate-400">No payments found</div>
          )}
        </CardContent>
      </Card>
    </div>
  );
}
