import { useState, useEffect } from 'react';
import { Plus, Lock, Unlock, Calendar, CheckCircle, X } from 'lucide-react';
import { PageHeader } from '@/components/common/PageHeader';
import { Button } from '@/components/ui/button';
import { StatusBadge } from '@/components/common/StatusBadge';
import { budgetService } from '@/services/budgetService';
import { FiscalYearDTO, CreateFiscalYearDTO } from '@/types/budget';
import { toast } from 'sonner';
import { format } from 'date-fns';
import { ptBR } from 'date-fns/locale';
import { ConfirmDialog } from '@/components/common/ConfirmDialog';
import { FiscalYearFormModal } from '../components/FiscalYearFormModal';

export function FiscalYearsPage() {
  const [fiscalYears, setFiscalYears] = useState<FiscalYearDTO[]>([]);
  const [currentFiscalYear, setCurrentFiscalYear] = useState<FiscalYearDTO | null>(null);
  const [loading, setLoading] = useState(true);
  const [isFormOpen, setIsFormOpen] = useState(false);
  const [isOpenDialog, setIsOpenDialog] = useState(false);
  const [isCloseDialog, setIsCloseDialog] = useState(false);
  const [selectedFiscalYear, setSelectedFiscalYear] = useState<FiscalYearDTO | null>(null);

  useEffect(() => {
    loadFiscalYears();
    loadCurrentFiscalYear();
  }, []);

  const loadFiscalYears = async () => {
    try {
      setLoading(true);
      const data = await budgetService.getFiscalYears();
      if (Array.isArray(data)) {
        setFiscalYears(data);
      } else {
        console.error("Dados inválidos recebidos:", data);
        setFiscalYears([]);
        toast.error("Formato de dados inválido recebido do servidor.");
      }
    } catch (error) {
      toast.error('Erro ao carregar exercícios fiscais');
    } finally {
      setLoading(false);
    }
  };

  const loadCurrentFiscalYear = async () => {
    try {
      const data = await budgetService.getCurrentFiscalYear();
      setCurrentFiscalYear(data);
    } catch (error) {
      // Pode não existir exercício corrente
      setCurrentFiscalYear(null);
    }
  };

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

  const handleOpen = (fiscalYear: FiscalYearDTO) => {
    setSelectedFiscalYear(fiscalYear);
    setIsOpenDialog(true);
  };

  const handleClose = (fiscalYear: FiscalYearDTO) => {
    setSelectedFiscalYear(fiscalYear);
    setIsCloseDialog(true);
  };

  const handleOpenConfirm = async () => {
    if (!selectedFiscalYear) return;
    try {
      await budgetService.openFiscalYear(selectedFiscalYear.id);
      toast.success('Exercício fiscal aberto com sucesso');
      setIsOpenDialog(false);
      setSelectedFiscalYear(null);
      loadFiscalYears();
      loadCurrentFiscalYear();
    } catch (error: any) {
      toast.error(error.message || 'Erro ao abrir exercício fiscal');
    }
  };

  const handleCloseConfirm = async () => {
    if (!selectedFiscalYear) return;
    try {
      await budgetService.closeFiscalYear(selectedFiscalYear.id);
      toast.success('Exercício fiscal fechado com sucesso');
      setIsCloseDialog(false);
      setSelectedFiscalYear(null);
      loadFiscalYears();
      loadCurrentFiscalYear();
    } catch (error: any) {
      toast.error(error.message || 'Erro ao fechar exercício fiscal');
    }
  };

  const handleFormSubmitData = async (data: CreateFiscalYearDTO) => {
    try {
      await budgetService.createFiscalYear(data);
      toast.success('Exercício fiscal criado com sucesso');
      setIsFormOpen(false);
      loadFiscalYears();
    } catch (error: any) {
      toast.error(error.message || 'Erro ao criar exercício fiscal');
    }
  };

  const getStatusBadge = (status: string) => {
    switch (status) {
      case 'DRAFT':
        return <StatusBadge status="draft" />;
      case 'OPEN':
        return <StatusBadge status="open" />;
      case 'CLOSED':
        return <StatusBadge status="closed" />;
      default:
        return <StatusBadge status={status} />;
    }
  };

  return (
    <div className="space-y-6">
      <PageHeader
        title="Exercícios Fiscais"
        description="Gestão de abertura e fechamento de exercícios fiscais"
        actions={
          <Button onClick={handleCreate} className="flex items-center gap-2">
            <Plus className="w-4 h-4" />
            Novo Exercício
          </Button>
        }
      />

      {currentFiscalYear && (
        <div className="bg-blue-50 border border-blue-200 rounded-lg p-4">
          <div className="flex items-center gap-2">
            <CheckCircle className="w-5 h-5 text-blue-600" />
            <div>
              <p className="font-semibold text-blue-900">
                Exercício Corrente: {currentFiscalYear.year}
              </p>
              <p className="text-sm text-blue-700">
                {format(new Date(currentFiscalYear.startDate), "dd 'de' MMMM", { locale: ptBR })} a{' '}
                {format(new Date(currentFiscalYear.endDate), "dd 'de' MMMM 'de' yyyy", { locale: ptBR })}
              </p>
            </div>
          </div>
        </div>
      )}

      <div className="bg-white rounded-lg shadow border">
        <div className="overflow-x-auto">
          <table className="min-w-full divide-y divide-gray-200">
            <thead className="bg-gray-50">
              <tr>
                <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                  Ano
                </th>
                <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                  Período
                </th>
                <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                  Status
                </th>
                <th className="px-6 py-3 text-right text-xs font-medium text-gray-500 uppercase tracking-wider">
                  Ações
                </th>
              </tr>
            </thead>
            <tbody className="bg-white divide-y divide-gray-200">
              {loading ? (
                <tr>
                  <td colSpan={4} className="px-6 py-4 text-center text-gray-500">
                    Carregando...
                  </td>
                </tr>
              ) : fiscalYears.length === 0 ? (
                <tr>
                  <td colSpan={4} className="px-6 py-4 text-center text-gray-500">
                    Nenhum exercício fiscal cadastrado
                  </td>
                </tr>
              ) : (
                fiscalYears.map((fy) => (
                  <tr key={fy.id} className="hover:bg-gray-50">
                    <td className="px-6 py-4 whitespace-nowrap">
                      <div className="flex items-center gap-2">
                        <Calendar className="w-4 h-4 text-gray-400" />
                        <span className="font-semibold text-gray-900">{fy.year}</span>
                      </div>
                    </td>
                    <td className="px-6 py-4 whitespace-nowrap text-sm text-gray-600">
                      {format(new Date(fy.startDate), "dd/MM/yyyy", { locale: ptBR })} -{' '}
                      {format(new Date(fy.endDate), "dd/MM/yyyy", { locale: ptBR })}
                    </td>
                    <td className="px-6 py-4 whitespace-nowrap">
                      {getStatusBadge(fy.status)}
                    </td>
                    <td className="px-6 py-4 whitespace-nowrap text-right text-sm font-medium">
                      <div className="flex justify-end gap-2">
                        {fy.status === 'DRAFT' && (
                          <Button
                            variant="outline"
                            size="sm"
                            onClick={() => handleOpen(fy)}
                            className="flex items-center gap-1"
                          >
                            <Unlock className="w-4 h-4" />
                            Abrir
                          </Button>
                        )}
                        {fy.status === 'OPEN' && (
                          <Button
                            variant="outline"
                            size="sm"
                            onClick={() => handleClose(fy)}
                            className="flex items-center gap-1"
                          >
                            <Lock className="w-4 h-4" />
                            Fechar
                          </Button>
                        )}
                      </div>
                    </td>
                  </tr>
                ))
              )}
            </tbody>
          </table>
        </div>
      </div>

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

      {/* Open Confirmation Dialog */}
      <ConfirmDialog
        open={isOpenDialog}
        onOpenChange={setIsOpenDialog}
        title="Abrir Exercício Fiscal"
        description={`Tem certeza que deseja abrir o exercício fiscal ${selectedFiscalYear?.year}?`}
        onConfirm={handleOpenConfirm}
      />

      {/* Close Confirmation Dialog */}
      <ConfirmDialog
        open={isCloseDialog}
        onOpenChange={setIsCloseDialog}
        title="Fechar Exercício Fiscal"
        description={`Tem certeza que deseja fechar o exercício fiscal ${selectedFiscalYear?.year}? Esta ação não pode ser desfeita.`}
        onConfirm={handleCloseConfirm}
        variant="destructive"
      />
    </div>
  );
}

