import { useState, useEffect } from 'react';
import { Plus, Edit, Eye, DollarSign, TrendingUp, TrendingDown, Wallet } 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 { BudgetLineDTO, CreateBudgetLineDTO } from '@/types/budget';
import { useMinistries } from '@/hooks/useMinistries';
import { useOrgUnits } from '@/hooks/useOrgUnits';
import { toast } from 'sonner';
import { formatCurrency } from '@/utils/locale';
import { AdvancedFilters } from '@/components/common/AdvancedFilters';
import { BudgetLineFormModal } from '../components/BudgetLineFormModal';
import { BudgetLineEntriesModal } from '../components/BudgetLineEntriesModal';

export function BudgetLinesPage() {
  const [budgetLines, setBudgetLines] = useState<BudgetLineDTO[]>([]);
  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 [selectedBudgetLine, setSelectedBudgetLine] = useState<BudgetLineDTO | null>(null);
  const [selectedLineForEntries, setSelectedLineForEntries] = useState<BudgetLineDTO | null>(null);
  const [filters, setFilters] = useState<{
    fiscalYearId?: string;
    ministryId?: string;
    orgUnitId?: string;
  }>({});
  const [search, setSearch] = useState('');
  const [pageSize, setPageSize] = useState(20);

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

  useEffect(() => {
    // Debounce search could be better, but for now simple effect
    const timer = setTimeout(() => {
      loadBudgetLines();
    }, 500);
    return () => clearTimeout(timer);
  }, [page, pageSize, filters, search]);

  const loadBudgetLines = async () => {
    try {
      setLoading(true);
      const response = await budgetService.getBudgetLines({
        page,
        size: pageSize,
        sortBy: 'code',
        sortDirection: 'ASC',
        ...filters,
        search,
      });
      setBudgetLines(response.content);
      setTotalPages(response.totalPages);
      setTotalElements(response.totalElements);
    } catch (error) {
      toast.error('Erro ao carregar linhas orçamentárias');
    } finally {
      setLoading(false);
    }
  };

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

  const handleEdit = (line: BudgetLineDTO) => {
    setSelectedBudgetLine(line);
    setIsFormOpen(true);
  };

  const handleFormSubmitData = async (data: CreateBudgetLineDTO) => {
    try {
      if (selectedBudgetLine) {
        await budgetService.updateBudgetLine(selectedBudgetLine.id, data);
        toast.success('Linha orçamentária atualizada com sucesso');
      } else {
        await budgetService.createBudgetLine(data);
        toast.success('Linha orçamentária criada com sucesso');
      }
      setIsFormOpen(false);
      setSelectedBudgetLine(null);
      loadBudgetLines();
    } catch (error: any) {
      toast.error(error.message || 'Erro ao salvar linha orçamentária');
    }
  };

  const [fiscalYears, setFiscalYears] = useState<{ id: string; year: number }[]>([]);

  useEffect(() => {
    const fetchFiscalYears = async () => {
      try {
        const data = await budgetService.getFiscalYears();
        setFiscalYears(data.map(fy => ({ id: fy.id, year: fy.year })));
      } catch (error) {
        console.error('Error fetching fiscal years for filters', error);
      }
    };
    fetchFiscalYears();
  }, []);

  const filterConfigs = [
    {
      key: 'fiscalYearId',
      label: 'Exercício Fiscal',
      type: 'select' as const,
      options: fiscalYears.map(fy => ({ value: fy.id, label: fy.year.toString() })),
    },
    {
      key: 'ministryId',
      label: 'Ministério',
      type: 'select' as const,
      options: ministries.map((m) => ({ value: m.id, label: m.name })),
    },
    {
      key: 'orgUnitId',
      label: 'Unidade Orgânica',
      type: 'select' as const,
      options: orgUnits.map((ou) => ({ value: ou.id, label: ou.name })),
    },
  ];

  const columns = [
    {
      key: 'code',
      header: 'Código',
      cell: (line: BudgetLineDTO) => (
        <span className="font-mono font-semibold">{line.code}</span>
      ),
    },
    {
      key: 'description',
      header: 'Descrição',
      cell: (line: BudgetLineDTO) => line.description,
    },
    {
      key: 'economicClass',
      header: 'Classificação',
      cell: (line: BudgetLineDTO) => (
        <span className="text-sm text-gray-600">{line.economicClass}</span>
      ),
    },
    {
      key: 'totalAllocated',
      header: 'Alocado',
      cell: (line: BudgetLineDTO) => (
        <span className="font-semibold text-green-600">
          {formatCurrency(line.totalAllocated || 0)}
        </span>
      ),
    },
    {
      key: 'totalCommitted',
      header: 'Comprometido',
      cell: (line: BudgetLineDTO) => (
        <span className="font-semibold text-orange-600">
          {formatCurrency(line.totalCommitted || 0)}
        </span>
      ),
    },
    {
      key: 'availableBalance',
      header: 'Disponível',
      cell: (line: BudgetLineDTO) => {
        const balance = line.availableBalance || 0;
        return (
          <span className={`font-semibold ${balance < 0 ? 'text-red-600' : 'text-blue-600'}`}>
            {formatCurrency(balance)}
          </span>
        );
      },
    },
    {
      key: 'actions',
      header: 'Ações',
      cell: (line: BudgetLineDTO) => (
        <div className="flex gap-2">
          <Button
            variant="ghost"
            size="sm"
            onClick={() => handleEdit(line)}
            className="text-blue-600 hover:bg-blue-50"
            title="Editar Estrutura"
          >
            <Edit className="w-4 h-4" />
          </Button>
          <Button
            variant="ghost"
            size="sm"
            onClick={() => setSelectedLineForEntries(line)}
            className="text-green-600 hover:bg-green-50"
            title="Gerir Dotações"
          >
            <Wallet className="w-4 h-4" />
          </Button>
        </div>
      ),
    },
  ];

  return (
    <div className="space-y-6">
      <PageHeader
        title="Linhas Orçamentárias"
        description="Gestão de linhas orçamentárias e visualização de saldos"
        actions={
          <Button onClick={handleCreate} className="flex items-center gap-2">
            <Plus className="w-4 h-4" />
            Nova Linha
          </Button>
        }
      />

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

      <ServerDataTable
        data={budgetLines}
        columns={columns}
        loading={loading}
        page={page}
        pageSize={pageSize}
        totalPages={totalPages}
        totalElements={totalElements}
        onPageChange={setPage}
        onPageSizeChange={(newPageSize) => {
          setPageSize(newPageSize);
          setPage(0);
        }}
        onSearch={setSearch}
      />

      <BudgetLineFormModal
        open={isFormOpen}
        onClose={() => {
          setIsFormOpen(false);
          setSelectedBudgetLine(null);
        }}
        onSubmit={handleFormSubmitData}
        budgetLine={selectedBudgetLine}
        ministries={ministries}
        orgUnits={orgUnits}
        fiscalYears={fiscalYears}
      />

      {/* Entries Modal (Allocations) */}
      <BudgetLineEntriesModal
        open={!!selectedLineForEntries}
        onClose={() => setSelectedLineForEntries(null)}
        budgetLine={selectedLineForEntries}
      />
    </div>
  );
}

