import { useState, useEffect } from 'react';
import { Eye, CheckCircle, XCircle, DollarSign } 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 { PaymentOrderDTO, UpdatePaymentOrderStatusDTO } from '@/types/treasury';
import { toast } from 'sonner';
import { formatCurrency } from '@/utils/locale';
import { format } from 'date-fns';
import { StatusBadge } from '@/components/common/StatusBadge';
import { AdvancedFilters } from '@/components/common/AdvancedFilters';
import { ConfirmDialog } from '@/components/common/ConfirmDialog';

export function PaymentOrdersPage() {
  const [orders, setOrders] = useState<PaymentOrderDTO[]>([]);
  const [loading, setLoading] = useState(true);
  const [page, setPage] = useState(0);
  const [totalPages, setTotalPages] = useState(0);
  const [totalElements, setTotalElements] = useState(0);
  const [isStatusDialogOpen, setIsStatusDialogOpen] = useState(false);
  const [selectedOrder, setSelectedOrder] = useState<PaymentOrderDTO | null>(null);
  const [newStatus, setNewStatus] = useState<string>('');
  const [filters, setFilters] = useState<{
    batchId?: string;
    status?: string;
  }>({});

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

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

  const handleStatusChange = (order: PaymentOrderDTO, status: string) => {
    setSelectedOrder(order);
    setNewStatus(status);
    setIsStatusDialogOpen(true);
  };

  const handleStatusConfirm = async () => {
    if (!selectedOrder) return;
    try {
      const dto: UpdatePaymentOrderStatusDTO = { status: newStatus as any };
      await treasuryService.updatePaymentOrderStatus(selectedOrder.id, dto);
      toast.success('Status da ordem atualizado com sucesso');
      setIsStatusDialogOpen(false);
      setSelectedOrder(null);
      loadOrders();
    } catch (error: any) {
      toast.error(error.message || 'Erro ao atualizar status da ordem');
    }
  };

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

  const filterConfigs = [
    {
      key: 'status',
      label: 'Status',
      type: 'select' as const,
      options: [
        { value: 'CREATED', label: 'Criada' },
        { value: 'SENT_TO_BANK', label: 'Enviada' },
        { value: 'PAID', label: 'Paga' },
        { value: 'REJECTED', label: 'Rejeitada' },
      ],
    },
  ];

  const columns = [
    {
      key: 'id',
      header: 'ID',
      cell: (order: PaymentOrderDTO) => (
        <span className="font-mono text-xs text-gray-500">{order.id.substring(0, 8)}...</span>
      ),
    },
    {
      key: 'grossAmount',
      header: 'Valor Bruto',
      cell: (order: PaymentOrderDTO) => (
        <span className="font-semibold text-gray-900">
          {formatCurrency(order.grossAmount)}
        </span>
      ),
    },
    {
      key: 'netAmount',
      header: 'Valor Líquido',
      cell: (order: PaymentOrderDTO) => (
        <span className="font-semibold text-green-600">
          {formatCurrency(order.netAmount)}
        </span>
      ),
    },
    {
      key: 'status',
      header: 'Status',
      cell: (order: PaymentOrderDTO) => getStatusBadge(order.status),
    },
    {
      key: 'actions',
      header: 'Ações',
      cell: (order: PaymentOrderDTO) => (
        <div className="flex gap-2">
          <Button
            variant="ghost"
            size="sm"
            onClick={async () => {
              try {
                const orderDetails = await treasuryService.getPaymentOrderById(order.id);
                toast.info(`Ordem: ${order.id}\nValor Bruto: ${formatCurrency(order.grossAmount)}\nValor Líquido: ${formatCurrency(order.netAmount)}\nStatus: ${order.status}`, {
                  duration: 5000,
                });
              } catch (error) {
                toast.error('Erro ao carregar detalhes da ordem');
              }
            }}
            className="text-blue-600 hover:bg-blue-50"
            title="Ver detalhes"
          >
            <Eye className="w-4 h-4" />
          </Button>
          {order.status === 'CREATED' && (
            <Button
              variant="outline"
              size="sm"
              onClick={() => handleStatusChange(order, 'SENT_TO_BANK')}
              className="flex items-center gap-1"
            >
              <CheckCircle className="w-4 h-4" />
              Enviar
            </Button>
          )}
        </div>
      ),
    },
  ];

  return (
    <div className="space-y-6">
      <PageHeader
        title="Ordens de Pagamento"
        description="Visualização e auditoria de ordens de pagamento individuais"
      />

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

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

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

