import { useState, useEffect } from 'react';
import { TrendingUp, TrendingDown, DollarSign, Filter, FileText, Table } from 'lucide-react';
import { PageHeader } from '@/components/common/PageHeader';
import { ServerDataTable } from '@/components/common/ServerDataTable';
import { Button } from '@/components/ui/button';
import { budgetService } from '@/services/budgetService';
import { BudgetExecutionDTO } from '@/types/budget';
import { toast } from 'sonner';
import { formatCurrency } from '@/utils/locale';
import { format } from 'date-fns';
import { AdvancedFilters } from '@/components/common/AdvancedFilters';
import { BudgetExecutionChart } from '../components/BudgetExecutionChart';

export function BudgetExecutionPage() {
  const [executions, setExecutions] = useState<BudgetExecutionDTO[]>([]);
  const [loading, setLoading] = useState(true);
  const [page, setPage] = useState(0);
  const [totalPages, setTotalPages] = useState(0);
  const [totalElements, setTotalElements] = useState(0);
  const [filters, setFilters] = useState<{
    budgetLineId?: string;
    periodId?: number;
    movementType?: string;
  }>({});

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

  const loadExecutions = async () => {
    try {
      setLoading(true);
      const response = await budgetService.getBudgetExecutions({
        page,
        size: 20,
        sortBy: 'createdAt',
        sortDirection: 'DESC',
        ...filters,
      });
      setExecutions(response.content);
      setTotalPages(response.totalPages);
      setTotalElements(response.totalElements);
    } catch (error) {
      toast.error('Erro ao carregar execuções orçamentárias');
    } finally {
      setLoading(false);
    }
  };

  const handleExport = async (format: 'pdf' | 'xlsx') => {
    try {
      await budgetService.exportBudgetExecution(format);
      toast.success(`Relatório ${format.toUpperCase()} gerado com sucesso`);
    } catch (error) {
      toast.error('Erro ao gerar relatório');
    }
  };

  const getMovementTypeBadge = (type: string) => {
    switch (type) {
      case 'COMMITMENT':
        return (
          <span className="px-2 py-1 text-xs font-semibold bg-orange-100 text-orange-700 rounded-full flex items-center gap-1">
            <TrendingUp className="w-3 h-3" />
            Compromisso
          </span>
        );
      case 'LIQUIDATION':
        return (
          <span className="px-2 py-1 text-xs font-semibold bg-blue-100 text-blue-700 rounded-full flex items-center gap-1">
            <DollarSign className="w-3 h-3" />
            Liquidação
          </span>
        );
      case 'PAYMENT':
        return (
          <span className="px-2 py-1 text-xs font-semibold bg-green-100 text-green-700 rounded-full flex items-center gap-1">
            <TrendingDown className="w-3 h-3" />
            Pagamento
          </span>
        );
      default:
        return <span className="px-2 py-1 text-xs font-semibold bg-gray-100 text-gray-700 rounded-full">{type}</span>;
    }
  };

  const filterConfigs = [
    {
      key: 'movementType',
      label: 'Tipo de Movimento',
      type: 'select' as const,
      options: [
        { value: 'COMMITMENT', label: 'Compromisso' },
        { value: 'LIQUIDATION', label: 'Liquidação' },
        { value: 'PAYMENT', label: 'Pagamento' },
      ],
    },
  ];

  const columns = [
    {
      key: 'budgetLineCode',
      header: 'Rubrica',
      cell: (execution: BudgetExecutionDTO) => (
        <span className="font-mono text-sm font-semibold text-gray-700">
          {execution.budgetLineCode || '-'}
        </span>
      ),
    },
    {
      key: 'description',
      header: 'Descrição',
      cell: (execution: BudgetExecutionDTO) => (
        <div className="max-w-xs truncate" title={execution.description || ''}>
          <span className="text-sm text-gray-900">{execution.description || '-'}</span>
        </div>
      ),
    },
    {
      key: 'movementType',
      header: 'Tipo',
      cell: (execution: BudgetExecutionDTO) => getMovementTypeBadge(execution.movementType),
    },
    {
      key: 'amount',
      header: 'Valor',
      cell: (execution: BudgetExecutionDTO) => (
        <span className="font-semibold text-gray-900">
          {formatCurrency(execution.amount)}
        </span>
      ),
    },
    {
      key: 'periodId',
      header: 'Período',
      cell: (execution: BudgetExecutionDTO) => {
        if (!execution.periodId) return '-';
        const periodStr = execution.periodId.toString();
        const year = periodStr.substring(0, 4);
        const month = periodStr.substring(4, 6);
        return `${month}/${year}`;
      },
    },
    {
      key: 'createdAt',
      header: 'Data',
      cell: (execution: BudgetExecutionDTO) => {
        if (!execution.createdAt) return '-';
        return format(new Date(execution.createdAt), 'dd/MM/yyyy HH:mm');
      },
    },
  ];

  return (
    <div className="space-y-6">
      <PageHeader
        title="Execução Orçamentária"
        description="Consulta de movimentos orçamentários (compromissos, liquidações e pagamentos)"
        actions={
          <div className="flex gap-2">
            <Button
              onClick={() => handleExport('pdf')}
              variant="outline"
              className="text-red-700 border-red-200 hover:bg-red-50"
            >
              <FileText className="w-4 h-4 mr-2" />
              PDF
            </Button>
            <Button
              onClick={() => handleExport('xlsx')}
              variant="outline"
              className="text-green-700 border-green-200 hover:bg-green-50"
            >
              <Table className="w-4 h-4 mr-2" />
              Excel
            </Button>
          </div>
        }
      />

      <div className="grid grid-cols-1 lg:grid-cols-4 gap-6">
        <div className="lg:col-span-1">
          <AdvancedFilters
            filters={filterConfigs}
            values={filters}
            onChange={(key, value) => {
              setFilters((prev) => ({ ...prev, [key]: value }));
              setPage(0);
            }}
            onReset={() => {
              setFilters({});
              setPage(0);
            }}
          />
        </div>
        <div className="lg:col-span-3">
          <BudgetExecutionChart data={executions} />
        </div>
      </div>

      <ServerDataTable
        data={executions}
        columns={columns}
        loading={loading}
        page={page}
        totalPages={totalPages}
        totalElements={totalElements}
        onPageChange={setPage}
      />
    </div>
  );
}

