
import { useState, useEffect } from "react";
import { useQuery, useMutation, useQueryClient } from "@tanstack/react-query";
import { Plus, Loader2, TrendingUp, AlertCircle } from "lucide-react";
import { format } from "date-fns";
import { toast } from "sonner";

import { Button } from "@/components/ui/button";
import {
    Dialog,
    DialogContent,
    DialogHeader,
    DialogTitle,
    DialogTrigger,
    DialogFooter,
} from "@/components/ui/dialog";
import {
    Select,
    SelectContent,
    SelectItem,
    SelectTrigger,
    SelectValue,
} from "@/components/ui/select";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { Card, CardContent, CardHeader, CardTitle, CardDescription } from "@/components/ui/card";

import { treasuryPlanService } from "@/services/treasuryPlanService";
import { CreateTreasuryPlanDTO } from "@/types/treasury";
import { TreasuryPlanList } from "../components/TreasuryPlanList";
import { formatCurrency } from "@/utils/locale";
import { ConfirmDialog } from "@/components/common/ConfirmDialog";

export function TreasuryPlanPage() {
    const queryClient = useQueryClient();
    const [isCreateOpen, setIsCreateOpen] = useState(false);
    const [isApproveDialogOpen, setIsApproveDialogOpen] = useState(false);
    const [planToApprove, setPlanToApprove] = useState<string | null>(null);
    const [formData, setFormData] = useState<CreateTreasuryPlanDTO>({
        fiscalYear: new Date().getFullYear(),
        referenceMonth: new Date().getMonth() + 1,
        approvedCeiling: 0,
    });

    // Current active plan
    const { data: activePlan } = useQuery({
        queryKey: ['active-treasury-plan'],
        queryFn: () => treasuryPlanService.findActivePlan(format(new Date(), 'yyyy-MM-dd')),
        retry: false, // Não tentar novamente se não houver plano (404 é esperado)
    });

    // All plans (status DRAFT by default, can act as a filter later)
    const { data: plans = [], isLoading } = useQuery({
        queryKey: ['treasury-plans'],
        queryFn: async () => {
            // Fetch all statuses and merge
            const drafts = await treasuryPlanService.findByStatus('DRAFT');
            const approved = await treasuryPlanService.findByStatus('APPROVED');
            const closed = await treasuryPlanService.findByStatus('CLOSED');
            return [...drafts, ...approved, ...closed].sort((a, b) =>
                (b.fiscalYear * 100 + b.referenceMonth) - (a.fiscalYear * 100 + a.referenceMonth)
            );
        },
    });

    const createMutation = useMutation({
        mutationFn: treasuryPlanService.create,
        onSuccess: () => {
            toast.success("Plano de tesouraria criado com sucesso");
            setIsCreateOpen(false);
            queryClient.invalidateQueries({ queryKey: ['treasury-plans'] });
        },
        onError: (error: any) => {
            toast.error(error.response?.data?.message || "Erro ao criar plano");
        },
    });

    const approveMutation = useMutation({
        mutationFn: async (id: string) => {
            // TODO: Obter approverId do contexto de autenticação
            const userData = localStorage.getItem('user');
            if (!userData) {
                throw new Error('Usuário não autenticado');
            }
            const user = JSON.parse(userData);
            return treasuryPlanService.approve(id, user.id);
        },
        onSuccess: () => {
            toast.success("Plano aprovado com sucesso");
            queryClient.invalidateQueries({ queryKey: ['treasury-plans'] });
            queryClient.invalidateQueries({ queryKey: ['active-treasury-plan'] });
            setIsApproveDialogOpen(false);
            setPlanToApprove(null);
        },
        onError: (error: any) => {
            toast.error(error.message || "Erro ao aprovar plano");
        },
    });

    const handleApproveClick = (id: string) => {
        setPlanToApprove(id);
        setIsApproveDialogOpen(true);
    };

    const handleApproveConfirm = () => {
        if (planToApprove) {
            approveMutation.mutate(planToApprove);
        }
    };

    const handleCreate = (e: React.FormEvent) => {
        e.preventDefault();
        createMutation.mutate(formData);
    };

    return (
        <div className="space-y-6">
            <div className="flex justify-between items-center">
                <div>
                    <h1 className="text-3xl font-bold tracking-tight">Planos de Tesouraria</h1>
                    <p className="text-muted-foreground">
                        Gerencie os tetos financeiros mensais (Controle Preventivo).
                    </p>
                </div>
                <Dialog open={isCreateOpen} onOpenChange={setIsCreateOpen}>
                    <DialogTrigger asChild>
                        <Button>
                            <Plus className="mr-2 h-4 w-4" />
                            Novo Plano
                        </Button>
                    </DialogTrigger>
                    <DialogContent>
                        <DialogHeader>
                            <DialogTitle>Novo Plano de Tesouraria</DialogTitle>
                        </DialogHeader>
                        <form onSubmit={handleCreate} className="space-y-4">
                            <div className="grid grid-cols-2 gap-4">
                                <div className="space-y-2">
                                    <Label>Ano Fiscal</Label>
                                    <Input
                                        type="number"
                                        value={formData.fiscalYear}
                                        onChange={(e) => setFormData({ ...formData, fiscalYear: parseInt(e.target.value) })}
                                        min={2024}
                                        max={2030}
                                    />
                                </div>
                                <div className="space-y-2">
                                    <Label>Mês de Referência</Label>
                                    <Select
                                        value={formData.referenceMonth.toString()}
                                        onValueChange={(val) => setFormData({ ...formData, referenceMonth: parseInt(val) })}
                                    >
                                        <SelectTrigger>
                                            <SelectValue />
                                        </SelectTrigger>
                                        <SelectContent>
                                            {Array.from({ length: 12 }, (_, i) => i + 1).map((m) => (
                                                <SelectItem key={m} value={m.toString()}>
                                                    {new Date(0, m - 1).toLocaleString('pt-BR', { month: 'long' })}
                                                </SelectItem>
                                            ))}
                                        </SelectContent>
                                    </Select>
                                </div>
                            </div>

                            <div className="space-y-2">
                                <Label>Teto Aprovado (XOF)</Label>
                                <Input
                                    type="number"
                                    value={formData.approvedCeiling}
                                    onChange={(e) => setFormData({ ...formData, approvedCeiling: parseFloat(e.target.value) })}
                                    min={0}
                                    step="0.01"
                                />
                            </div>

                            <DialogFooter>
                                <Button variant="outline" type="button" onClick={() => setIsCreateOpen(false)}>
                                    Cancelar
                                </Button>
                                <Button type="submit" disabled={createMutation.isPending}>
                                    {createMutation.isPending && <Loader2 className="mr-2 h-4 w-4 animate-spin" />}
                                    Criar Plano
                                </Button>
                            </DialogFooter>
                        </form>
                    </DialogContent>
                </Dialog>
            </div>

            {activePlan && (
                <Card className="bg-primary/5 border-primary/20">
                    <CardHeader>
                        <CardTitle className="flex items-center gap-2 text-primary">
                            <TrendingUp className="h-5 w-5" />
                            Plano Ativo: {activePlan.fiscalYear}/{activePlan.referenceMonth.toString().padStart(2, '0')}
                        </CardTitle>
                        <CardDescription>
                            Status atual da execução orçamentária para o mês corrente.
                        </CardDescription>
                    </CardHeader>
                    <CardContent className="grid gap-4 md:grid-cols-4">
                        <div>
                            <p className="text-sm font-medium text-muted-foreground">Teto Aprovado</p>
                            <div className="text-2xl font-bold">{formatCurrency(activePlan.approvedCeiling)}</div>
                        </div>
                        <div>
                            <p className="text-sm font-medium text-muted-foreground">Executado</p>
                            <div className="text-2xl font-bold text-yellow-600">{formatCurrency(activePlan.executedAmount)}</div>
                        </div>
                        <div>
                            <p className="text-sm font-medium text-muted-foreground">Disponível</p>
                            <div className="text-2xl font-bold text-green-600">{formatCurrency(activePlan.availableAmount)}</div>
                        </div>
                        <div>
                            <p className="text-sm font-medium text-muted-foreground">Percentual</p>
                            <div className="text-2xl font-bold">
                                {((activePlan.executedAmount / activePlan.approvedCeiling) * 100).toFixed(1)}%
                            </div>
                        </div>
                    </CardContent>
                </Card>
            )}

            {isLoading ? (
                <div className="flex justify-center p-8">
                    <Loader2 className="h-8 w-8 animate-spin text-muted-foreground" />
                </div>
            ) : (
                <TreasuryPlanList
                    plans={plans}
                    onApprove={handleApproveClick}
                    isLoading={approveMutation.isPending}
                />
            )}

            <ConfirmDialog
                open={isApproveDialogOpen}
                onOpenChange={setIsApproveDialogOpen}
                title="Aprovar Plano de Tesouraria"
                description="Tem certeza que deseja aprovar este plano? Esta ação é irreversível e ativará o plano para o período especificado."
                confirmLabel="Aprovar"
                cancelLabel="Cancelar"
                onConfirm={handleApproveConfirm}
            />
        </div>
    );
}
