import { useState, useEffect } from 'react';
import { Plus } from 'lucide-react';
import { PageHeader } from '@/components/common/PageHeader';
import { ServerDataTable } from '@/components/common/ServerDataTable';
import { Button } from '@/components/ui/button';
import { treasuryService } from '@/services/treasuryService';
import { TreasuryPaymentDTO } from '@/types/treasury';
import { toast } from 'sonner';
import { format } from 'date-fns';
import { StatusBadge } from '@/components/common/StatusBadge';
import { AdvancedFilters } from '@/components/common/AdvancedFilters';
import { TreasuryPaymentFormModal } from '../components/TreasuryPaymentFormModal';

export function TreasuryPaymentsPage() {
  const [payments, setPayments] = useState<TreasuryPaymentDTO[]>([]);
  const [loading, setLoading] = useState(true);
  const [page, setPage] = useState(0);
  const [totalPages, setTotalPages] = useState(0);
  const [totalElements, setTotalElements] = useState(0);
  const [isFormOpen, setIsFormOpen] = useState(false);
  const [filters, setFilters] = useState<{
    paymentOrderId?: string;
    status?: string;
  }>({});

  useEffect(() => {
    loadPayments();
  }, [page, filters]);

  const loadPayments = async () => {
    try {
      setLoading(true);
      const response = await treasuryService.getTreasuryPayments({
        page,
        size: 20,
        sortBy: 'paidAt',
        sortDirection: 'DESC',
        ...filters,
      });
      setPayments(response.content);
      setTotalPages(response.totalPages);
      setTotalElements(response.totalElements);
    } catch (error) {
      toast.error('Erro ao carregar confirmações de pagamento');
    } finally {
      setLoading(false);
    }
  };

  const handleCreate = () => {
    setIsFormOpen(true);
  };

  const handleFormSuccess = () => {
    loadPayments();
  };

  const getStatusBadge = (status: string) => {
    switch (status) {
      case 'PENDING':
        return <StatusBadge status="pending" />;
      case 'PAID':
        return <StatusBadge status="paid" />;
      case 'REJECTED':
        return <StatusBadge status="rejected" />;
      case 'CANCELLED':
        return <StatusBadge status="cancelled" />;
      default:
        return <StatusBadge status="draft" />;
    }
  };

  const filterConfigs = [
    {
      key: 'status',
      label: 'Status',
      type: 'select' as const,
      options: [
        { value: 'PENDING', label: 'Pendente' },
        { value: 'PAID', label: 'Pago' },
        { value: 'REJECTED', label: 'Rejeitado' },
        { value: 'CANCELLED', label: 'Cancelado' },
      ],
    },
  ];

  const columns = [
    {
      key: 'paymentOrderId',
      header: 'Ordem de Pagamento',
      cell: (payment: TreasuryPaymentDTO) => (
        <span className="font-mono text-xs text-gray-500">
          {payment.paymentOrderId.substring(0, 8)}...
        </span>
      ),
    },
    {
      key: 'transactionRef',
      header: 'Referência',
      cell: (payment: TreasuryPaymentDTO) => (
        <span className="font-mono text-sm">{payment.transactionRef || '-'}</span>
      ),
    },
    {
      key: 'status',
      header: 'Status',
      cell: (payment: TreasuryPaymentDTO) => getStatusBadge(payment.status),
    },
    {
      key: 'paidAt',
      header: 'Data de Pagamento',
      cell: (payment: TreasuryPaymentDTO) => {
        if (!payment.paidAt) return '-';
        return format(new Date(payment.paidAt), 'dd/MM/yyyy HH:mm');
      },
    },
    {
      key: 'message',
      header: 'Mensagem',
      cell: (payment: TreasuryPaymentDTO) => (
        <span className="text-sm text-gray-600">{payment.message || '-'}</span>
      ),
    },
  ];

  return (
    <div className="space-y-6">
      <PageHeader
        title="Confirmações de Pagamento"
        description="Registro e consulta de confirmações de pagamento efetivadas"
        actions={
          <Button onClick={handleCreate} className="flex items-center gap-2">
            <Plus className="w-4 h-4" />
            Nova Confirmação
          </Button>
        }
      />

      <AdvancedFilters
        filters={filterConfigs}
        values={filters}
        onChange={(key, value) => setFilters((prev) => ({ ...prev, [key]: value }))}
        onReset={() => setFilters({})}
      />

      <ServerDataTable
        data={payments}
        columns={columns}
        loading={loading}
        page={page}
        totalPages={totalPages}
        totalElements={totalElements}
        onPageChange={setPage}
      />

      <TreasuryPaymentFormModal
        open={isFormOpen}
        onClose={() => setIsFormOpen(false)}
        onSuccess={handleFormSuccess}
      />
    </div>
  );
}

