import { useState, useEffect } from 'react';
import { Plus, Send, CheckCircle, XCircle, Clock, Eye } 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 { PaymentBatchDTO, CreatePaymentBatchDTO, UpdatePaymentBatchStatusDTO } from '@/types/treasury';
import { useMinistries } from '@/hooks/useMinistries';
import { toast } from 'sonner';
import { format } from 'date-fns';
import { StatusBadge } from '@/components/common/StatusBadge';
import { AdvancedFilters } from '@/components/common/AdvancedFilters';
import { ConfirmDialog } from '@/components/common/ConfirmDialog';
import { PaymentBatchFormModal } from '../components/PaymentBatchFormModal';

export function PaymentBatchesPage() {
  const [batches, setBatches] = useState<PaymentBatchDTO[]>([]);
  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 [isStatusDialogOpen, setIsStatusDialogOpen] = useState(false);
  const [selectedBatch, setSelectedBatch] = useState<PaymentBatchDTO | null>(null);
  const [newStatus, setNewStatus] = useState<string>('');
  const [filters, setFilters] = useState<{
    periodId?: number;
    ministryId?: string;
    status?: string;
  }>({});

  const { ministries } = useMinistries({ size: 100 });

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

  const loadBatches = async () => {
    try {
      setLoading(true);
      const response = await treasuryService.getPaymentBatches({
        page,
        size: 20,
        sortBy: 'createdAt',
        sortDirection: 'DESC',
        ...filters,
      });
      setBatches(response.content);
      setTotalPages(response.totalPages);
      setTotalElements(response.totalElements);
    } catch (error) {
      toast.error('Erro ao carregar lotes de pagamento');
    } finally {
      setLoading(false);
    }
  };

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

  const handleStatusChange = (batch: PaymentBatchDTO, status: string) => {
    setSelectedBatch(batch);
    setNewStatus(status);
    setIsStatusDialogOpen(true);
  };

  const handleStatusConfirm = async () => {
    if (!selectedBatch) return;
    try {
      const dto: UpdatePaymentBatchStatusDTO = { status: newStatus as any };
      await treasuryService.updatePaymentBatchStatus(selectedBatch.id, dto);
      toast.success('Status do lote atualizado com sucesso');
      setIsStatusDialogOpen(false);
      setSelectedBatch(null);
      loadBatches();
    } catch (error: any) {
      toast.error(error.message || 'Erro ao atualizar status do lote');
    }
  };

  const handleFormSubmitData = async (data: CreatePaymentBatchDTO) => {
    try {
      await treasuryService.createPaymentBatch(data);
      toast.success('Lote de pagamento criado com sucesso');
      setIsFormOpen(false);
      loadBatches();
    } catch (error: any) {
      toast.error(error.message || 'Erro ao criar lote de pagamento');
    }
  };

  const getStatusBadge = (status: string) => {
    switch (status) {
      case 'CREATED':
        return <StatusBadge status="created" />;
      case 'SENT_TO_BANK':
        return <StatusBadge status="sent_to_bank" />;
      case 'CONFIRMED':
        return <StatusBadge status="confirmed" />;
      case 'REJECTED':
        return <StatusBadge status="rejected" />;
      default:
        return <StatusBadge status={status} />;
    }
  };

  const filterConfigs = [
    {
      key: 'ministryId',
      label: 'Ministério',
      type: 'select' as const,
      options: ministries.map((m) => ({ value: m.id, label: m.name })),
    },
    {
      key: 'status',
      label: 'Status',
      type: 'select' as const,
      options: [
        { value: 'CREATED', label: 'Criado' },
        { value: 'SENT_TO_BANK', label: 'Enviado' },
        { value: 'CONFIRMED', label: 'Confirmado' },
        { value: 'REJECTED', label: 'Rejeitado' },
      ],
    },
  ];

  const columns = [
    {
      key: 'periodId',
      header: 'Período',
      cell: (batch: PaymentBatchDTO) => {
        const periodStr = batch.periodId.toString();
        const year = periodStr.substring(0, 4);
        const month = periodStr.substring(4, 6);
        return `${month}/${year}`;
      },
    },
    {
      key: 'ministryId',
      header: 'Ministério',
      cell: (batch: PaymentBatchDTO) => {
        const ministry = ministries.find((m) => m.id === batch.ministryId);
        return ministry?.name || batch.ministryId;
      },
    },
    {
      key: 'status',
      header: 'Status',
      cell: (batch: PaymentBatchDTO) => getStatusBadge(batch.status),
    },
    {
      key: 'createdAt',
      header: 'Criado em',
      cell: (batch: PaymentBatchDTO) => {
        if (!batch.createdAt) return '-';
        return format(new Date(batch.createdAt), 'dd/MM/yyyy HH:mm');
      },
    },
    {
      key: 'actions',
      header: 'Ações',
      cell: (batch: PaymentBatchDTO) => (
        <div className="flex gap-2">
          {batch.status === 'CREATED' && (
            <Button
              variant="outline"
              size="sm"
              onClick={() => handleStatusChange(batch, 'SENT_TO_BANK')}
              className="flex items-center gap-1"
            >
              <Send className="w-4 h-4" />
              Enviar
            </Button>
          )}
        </div>
      ),
    },
  ];

  return (
    <div className="space-y-6">
      <PageHeader
        title="Lotes de Pagamento"
        description="Criação e envio de lotes de pagamento para o Banco Central"
        actions={
          <Button onClick={handleCreate} className="flex items-center gap-2">
            <Plus className="w-4 h-4" />
            Novo Lote
          </Button>
        }
      />

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

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

      {/* Form Modal */}
      <PaymentBatchFormModal
        open={isFormOpen}
        onClose={() => setIsFormOpen(false)}
        onSubmit={handleFormSubmitData}
        ministries={ministries}
      />

      {/* Status Change Dialog */}
      <ConfirmDialog
        open={isStatusDialogOpen}
        onOpenChange={setIsStatusDialogOpen}
        title="Alterar Status do Lote"
        description={`Tem certeza que deseja alterar o status do lote para "${newStatus}"?`}
        onConfirm={handleStatusConfirm}
      />
    </div>
  );
}

