'use client';

import { useState } from 'react';
import { useQuery } from '@tanstack/react-query';
import { Download } from 'lucide-react';
import DataTable from '@/components/ui/DataTable';
import Badge from '@/components/ui/Badge';
import ActionButton from '@/components/ui/ActionButton';
import Modal from '@/components/ui/Modal';
import { paymentsApi } from '@/lib/api';
import { formatDateTime, formatCurrency } from '@/lib/utils';

export default function PaymentsPage() {
  const [filters, setFilters] = useState({ search: '', status: '', method: '' });
  const [exportModalOpen, setExportModalOpen] = useState(false);
  const [exportDateFrom, setExportDateFrom] = useState('');
  const [exportDateTo, setExportDateTo] = useState('');
  const [exportColumns, setExportColumns] = useState<Record<string, boolean>>({
    reference: true, booking: true, amount: true, method: true, status: true, createdAt: true,
  });

  const { data, isLoading } = useQuery({
    queryKey: ['payments', filters],
    queryFn: () => paymentsApi.getAll({
      search: filters.search || undefined,
      status: filters.status || undefined,
      method: filters.method || undefined,
    }),
  });

  const confirmExport = () => {
    const cols = Object.entries(exportColumns).filter(([, v]) => v).map(([k]) => k);
    if (cols.length === 0) { alert('Please select at least one column'); return; }

    const items = ((data as any)?.items || (Array.isArray(data) ? data : [])) as any[];
    const exportItems = items.filter((p: any) => {
      if (!exportDateFrom && !exportDateTo) return true;
      const d = p.createdAt ? new Date(p.createdAt).toISOString().split('T')[0] : null;
      if (exportDateFrom && (!d || d < exportDateFrom)) return false;
      if (exportDateTo && (!d || d > exportDateTo)) return false;
      return true;
    });

    const csv = [
      cols.join(','),
      ...exportItems.map((payment: any) => {
        const values = cols.map(col => {
          switch (col) {
            case 'reference': return payment.reference || payment.id?.substring(0, 8) || '';
            case 'booking': return payment.booking?.bookingRef || 'N/A';
            case 'amount': return formatCurrency(payment.amountMinor, payment.currency);
            case 'method': return payment.method || '';
            case 'status': return payment.status || '';
            case 'createdAt': return payment.createdAt || '';
            default: return '';
          }
        });
        return values.map(v => `"${v}"`).join(',');
      }),
    ].join('\n');

    const blob = new Blob([csv], { type: 'text/csv' });
    const url = window.URL.createObjectURL(blob);
    const a = document.createElement('a');
    a.href = url;
    a.download = `payments-${new Date().toISOString().split('T')[0]}.csv`;
    a.click();
    setExportModalOpen(false);
  };

  const columns = [
    { key: 'reference', label: 'Reference', render: (payment: any) => <span className="font-mono">{payment.reference || payment.id?.substring(0, 8)}</span> },
    { key: 'booking', label: 'Booking', render: (payment: any) => payment.booking?.bookingRef || 'N/A' },
    { key: 'amount', label: 'Amount', render: (payment: any) => formatCurrency(payment.amountMinor, payment.currency) },
    { key: 'method', label: 'Method', render: (payment: any) => <Badge>{payment.method}</Badge> },
    { key: 'status', label: 'Status', render: (payment: any) => <Badge variant="status" status={payment.status}>{payment.status}</Badge> },
    { key: 'createdAt', label: 'Created', render: (payment: any) => formatDateTime(payment.createdAt) },
  ];

  return (
    <div className="space-y-6">
      <div className="flex items-center justify-between">
        <div>
          <h1 className="text-2xl font-bold text-foreground">Payments</h1>
          <p className="text-muted-foreground">Manage payment transactions and refunds</p>
        </div>
        <ActionButton icon={Download} variant="secondary" onClick={() => setExportModalOpen(true)}>Export</ActionButton>
      </div>

      <div className="card">
        <div className="grid grid-cols-1 md:grid-cols-3 gap-4">
          <div>
            <label className="label">Search</label>
            <input type="text" placeholder="Search..." className="input" value={filters.search} onChange={(e) => setFilters({ ...filters, search: e.target.value })} />
          </div>
          <div>
            <label className="label">Status</label>
            <select className="input" value={filters.status} onChange={(e) => setFilters({ ...filters, status: e.target.value })}>
              <option value="">All Status</option>
              <option value="PENDING">Pending</option>
              <option value="COMPLETED">Completed</option>
              <option value="FAILED">Failed</option>
            </select>
          </div>
          <div>
            <label className="label">Method</label>
            <select className="input" value={filters.method} onChange={(e) => setFilters({ ...filters, method: e.target.value })}>
              <option value="">All Methods</option>
              <option value="TELEBIRR">Telebirr</option>
              <option value="CBE_BIRR">CBE Birr</option>
              <option value="EBIRR">eBirr</option>
              <option value="CARD">Card</option>
              <option value="WALLET">Wallet</option>
              <option value="CASH">Cash</option>
            </select>
          </div>
        </div>
      </div>

      <DataTable
        data={(data as any)?.items || (Array.isArray(data) ? data : [])}
        columns={columns}
        actions={[]}
        loading={isLoading}
        emptyMessage="No payments found"
      />

      {/* Export Modal */}
      <Modal isOpen={exportModalOpen} onClose={() => setExportModalOpen(false)} title="Export Payments" size="md">
        <div className="space-y-4">
          <div className="grid grid-cols-2 gap-4">
            <div>
              <label className="label">Date From</label>
              <input type="date" className="input" value={exportDateFrom} onChange={(e) => setExportDateFrom(e.target.value)} />
            </div>
            <div>
              <label className="label">Date To</label>
              <input type="date" className="input" value={exportDateTo} onChange={(e) => setExportDateTo(e.target.value)} />
            </div>
          </div>

          <div>
            <p className="text-sm font-medium mb-2">Select Columns</p>
            <div className="space-y-2">
              {[
                { key: 'reference', label: 'Reference' },
                { key: 'booking', label: 'Booking Reference' },
                { key: 'amount', label: 'Amount' },
                { key: 'method', label: 'Payment Method' },
                { key: 'status', label: 'Status' },
                { key: 'createdAt', label: 'Created At' },
              ].map((col) => (
                <label key={col.key} className="flex items-center gap-3 p-2 hover:bg-gray-50 dark:hover:bg-gray-900/50 rounded cursor-pointer">
                  <input
                    type="checkbox"
                    checked={exportColumns[col.key] || false}
                    onChange={(e) => setExportColumns({ ...exportColumns, [col.key]: e.target.checked })}
                    className="w-4 h-4 rounded border-gray-300"
                  />
                  <span className="text-sm font-medium">{col.label}</span>
                </label>
              ))}
            </div>
          </div>

          <div className="flex justify-end gap-2 pt-4 border-t">
            <ActionButton variant="secondary" onClick={() => setExportModalOpen(false)}>Cancel</ActionButton>
            <ActionButton onClick={confirmExport}>Export CSV</ActionButton>
          </div>
        </div>
      </Modal>
    </div>
  );
}
