"use client";

import { useState, useEffect, useRef } from "react";
import { Button } from "@/components/ui/button";
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card";
import { Database, Loader2, RefreshCw, Trash2, AlertTriangle, CheckCircle2, XCircle, Terminal } from "lucide-react";
import { getSeederApiUrl } from "@/lib/config";
import { toast } from "sonner";
import {
    Dialog,
    DialogContent,
    DialogDescription,
    DialogFooter,
    DialogHeader,
    DialogTitle,
} from "@/components/ui/dialog";
import { ScrollArea } from "@/components/ui/scroll-area";
import { cn } from "@/lib/utils";

export default function SeederPage() {
    const [isSeeding, setIsSeeding] = useState(false);
    const [isResetting, setIsResetting] = useState(false);

    // Log Dialog State
    const [showLogDialog, setShowLogDialog] = useState(false);
    const [logs, setLogs] = useState<string[]>([]);
    const [processStatus, setProcessStatus] = useState<'idle' | 'running' | 'success' | 'error'>('idle');
    const scrollEndRef = useRef<HTMLDivElement>(null);

    const [showConfirmDialog, setShowConfirmDialog] = useState(false);

    // Auto-scroll to bottom of logs
    useEffect(() => {
        if (scrollEndRef.current) {
            scrollEndRef.current.scrollIntoView({ behavior: "smooth" });
        }
    }, [logs]);

    const handleStream = async (endpoint: string, type: 'seed' | 'reset') => {
        setLogs([]);
        setProcessStatus('running');
        setShowLogDialog(true);
        if (type === 'seed') setIsSeeding(true);
        else setIsResetting(true);

        try {
            // For now, only /seed supports streaming in the backend v2 we implemented
            // Check if backend supports stream. if not fallback? 
            // We implemented /seed/stream in server.js today.
            // But /reset might not support it yet unless updated. 
            // Let's assume /reset is still legacy POST for now, or update it later.
            // Actually, for consistency, let's keep /reset as POST but show a simple loader, 
            // or better, implement /reset/stream too? 
            // The user asked for "log popup" primarily for seeding content.

            if (type === 'reset') {
                // Legacy Reset (POST) - Mimic stream output
                setLogs(['🚀 Starting flush/reset process...']);
                const res = await fetch(`${getSeederApiUrl()}/reset`, {
                    method: 'POST',
                    headers: { 'Content-Type': 'application/json' }, // Fix for Express parsing empty body if needed
                    body: JSON.stringify({}) // Explicit empty body
                });
                const data = await res.json();
                if (res.ok) {
                    setLogs(prev => [...prev, '✅ Reset completed successfully!', JSON.stringify(data, null, 2)]);
                    setProcessStatus('success');
                    toast.success("Banco resetado com sucesso!");
                } else {
                    setLogs(prev => [...prev, '❌ Reset failed.', data.message]);
                    setProcessStatus('error');
                    toast.error("Erro ao resetar");
                }
                return;
            }

            // Real Streaming for Seed
            const eventSource = new EventSource(`${getSeederApiUrl()}/seed/stream?type=full`);

            eventSource.onmessage = (event) => {
                try {
                    const data = JSON.parse(event.data);

                    if (data.message) {
                        setLogs(prev => [...prev, data.message]);
                    }

                    if (data.type === 'done') {
                        setProcessStatus('success');
                        eventSource.close();
                        toast.success("Processo concluído!");
                    } else if (data.type === 'error') {
                        setProcessStatus('error');
                        setLogs(prev => [...prev, `❌ Error: ${data.error}`]);
                        eventSource.close();
                        toast.error("Processo falhou");
                    }
                } catch (e) {
                    console.error("Parse error", e);
                }
            };

            eventSource.onerror = (err) => {
                // Determine if it was a connection error or just closed
                if (processStatus !== 'success') {
                    // setLogs(prev => [...prev, '⚠️ Connection closed or error.']);
                    // Often EventSource reconnects, so we don't assume fatal error immediately unless closed manually
                    // But for this one-shot script, we usually close on success.
                    // If we get error before success, it's an issue.
                    // Let's rely on the explicit 'done'/'error' messages.
                    eventSource.close();
                }
            };

        } catch (error) {
            console.error(error);
            setProcessStatus('error');
            setLogs(prev => [...prev, String(error)]);
        } finally {
            if (type === 'reset') {
                setIsResetting(false);
            }
            // setIsSeeding is cleared when dialog closes or execution finishes
        }
    };

    const closeDialog = () => {
        if (processStatus === 'running') return; // Prevent closing while running? Or allow background?
        setShowLogDialog(false);
        setIsSeeding(false);
        setIsResetting(false);
    };

    return (
        <div className="container mx-auto py-6 space-y-6">
            <div>
                <h1 className="text-3xl font-bold text-foreground">🌱 Seeder & Reset</h1>
                <p className="text-muted-foreground mt-2">
                    Gerencie o estado do banco de dados de desenvolvimento
                </p>
            </div>

            <div className="grid gap-6 md:grid-cols-2">
                {/* Seed Card */}
                <Card className="border-l-4 border-l-green-500 shadow-sm">
                    <CardHeader>
                        <CardTitle className="flex items-center gap-2 text-green-700 dark:text-green-400">
                            <Database className="h-6 w-6" />
                            Popular Banco de Dados
                        </CardTitle>
                        <CardDescription>
                            Injeta dados massivos para teste e desenvolvimento
                        </CardDescription>
                    </CardHeader>
                    <CardContent className="space-y-4">
                        <div className="bg-muted/50 p-4 rounded-lg text-sm space-y-2 border border-border">
                            <h4 className="font-semibold flex items-center gap-2">
                                <CheckCircle2 className="h-4 w-4 text-green-500" />
                                O que será criado:
                            </h4>
                            <ul className="list-disc list-inside text-muted-foreground ml-1 space-y-1">
                                <li>Empresas (ACME, Stark, fake generates)</li>
                                <li>Usuários (Recruiters, Candidates, Admins)</li>
                                <li>Vagas de emprego e Candidaturas</li>
                                <li>Cidades, Estados e Países</li>
                                <li>Tickets e Notificações</li>
                            </ul>
                        </div>
                        <Button
                            onClick={() => handleStream('seed', 'seed')}
                            disabled={isSeeding || isResetting}
                            className="w-full bg-green-600 hover:bg-green-700 text-white font-semibold h-12 text-lg shadow-md transition-all hover:scale-[1.02]"
                        >
                            {isSeeding ? <Loader2 className="mr-2 h-5 w-5 animate-spin" /> : <RefreshCw className="mr-2 h-5 w-5" />}
                            Executar Seed Completo
                        </Button>
                    </CardContent>
                </Card>

                {/* Reset Card */}
                <Card className="border-l-4 border-l-destructive shadow-sm">
                    <CardHeader>
                        <CardTitle className="flex items-center gap-2 text-destructive">
                            <AlertTriangle className="h-6 w-6" />
                            Resetar / Limpar Banco
                        </CardTitle>
                        <CardDescription>
                            Ação destrutiva para limpar o ambiente
                        </CardDescription>
                    </CardHeader>
                    <CardContent className="space-y-4">
                        <div className="bg-destructive/10 p-4 rounded-lg text-sm space-y-2 border border-destructive/20">
                            <h4 className="font-semibold flex items-center gap-2 text-destructive">
                                <XCircle className="h-4 w-4" />
                                O que será apagado:
                            </h4>
                            <ul className="list-disc list-inside text-destructive/80 ml-1 space-y-1">
                                <li>Todas as empresas e vagas</li>
                                <li>Todos os usuários (exceto SuperAdmin)</li>
                                <li>Candidaturas e históricos</li>
                                <li>Logs e notificações</li>
                            </ul>
                        </div>
                        <Button
                            onClick={() => setShowConfirmDialog(true)}
                            disabled={isSeeding || isResetting}
                            className="w-full"
                            variant="destructive"
                            size="lg"
                        >
                            {isResetting ? <Loader2 className="mr-2 h-5 w-5 animate-spin" /> : <Trash2 className="mr-2 h-5 w-5" />}
                            Apagar Tudo (Reset)
                        </Button>
                    </CardContent>
                </Card>
            </div>

            {/* Log Dialog */}
            <Dialog open={showLogDialog} onOpenChange={(open) => { if (!open && processStatus !== 'running') closeDialog(); }}>
                <DialogContent className="max-w-4xl h-[80vh] flex flex-col p-6 gap-4">
                    <DialogHeader className="shrink-0 space-y-2">
                        <DialogTitle className="flex items-center gap-2 text-2xl">
                            {processStatus === 'running' && <Loader2 className="h-6 w-6 animate-spin text-blue-500" />}
                            {processStatus === 'success' && <CheckCircle2 className="h-6 w-6 text-green-500" />}
                            {processStatus === 'error' && <XCircle className="h-6 w-6 text-destructive" />}
                            Console de execução
                        </DialogTitle>
                        <DialogDescription className="text-base text-gray-500">
                            Acompanhe o progresso da operação em tempo real.
                        </DialogDescription>
                    </DialogHeader>

                    {/* Terminal Window */}
                    <div className="flex-1 min-h-0 bg-slate-950 rounded-lg border border-slate-800 shadow-inner flex flex-col font-mono text-sm overflow-hidden relative group">
                        {/* Terminal Header */}
                        <div className="bg-slate-900 px-4 py-2 border-b border-slate-800 flex items-center gap-2 text-slate-400 text-xs">
                            <Terminal className="h-3 w-3" />
                            <span>root@gohorse-seeder:~# script.sh</span>
                        </div>

                        {/* Scrollable Logs */}
                        <div className="flex-1 overflow-auto p-4 space-y-1 text-slate-300">
                            {logs.length === 0 && processStatus === 'idle' && (
                                <div className="opacity-50 italic">Aguardando início...</div>
                            )}
                            {logs.map((log, i) => (
                                <div key={i} className="break-words leading-relaxed animate-in fade-in slide-in-from-left-2 duration-300">
                                    <span className="opacity-50 mr-2 select-none">
                                        {new Date().toLocaleTimeString()}
                                    </span>
                                    {log.includes('❌') ? (
                                        <span className="text-red-400 font-bold">{log}</span>
                                    ) : log.includes('✅') ? (
                                        <span className="text-green-400 font-bold">{log}</span>
                                    ) : log.includes('🚀') ? (
                                        <span className="text-blue-400 font-bold underline">{log}</span>
                                    ) : (
                                        <span>{log}</span>
                                    )}
                                </div>
                            ))}
                            <div ref={scrollEndRef} />
                        </div>
                    </div>

                    <DialogFooter className="shrink-0 sm:justify-between">
                        <div className="flex items-center text-sm text-muted-foreground">
                            Status: <span className={cn("ml-2 font-medium capitalize", {
                                'text-blue-500': processStatus === 'running',
                                'text-green-500': processStatus === 'success',
                                'text-red-500': processStatus === 'error'
                            })}>{processStatus}</span>
                        </div>
                        <Button
                            onClick={closeDialog}
                            variant={processStatus === 'running' ? 'ghost' : 'default'}
                            disabled={processStatus === 'running'}
                        >
                            {processStatus === 'running' ? 'Executando...' : 'Fechar'}
                        </Button>
                    </DialogFooter>
                </DialogContent>
            </Dialog>

            {/* Confirmation Dialog */}
            <Dialog open={showConfirmDialog} onOpenChange={setShowConfirmDialog}>
                <DialogContent>
                    <DialogHeader>
                        <DialogTitle className="flex items-center gap-2 text-destructive">
                            <AlertTriangle className="h-6 w-6" />
                            Atenção Absoluta!
                        </DialogTitle>
                        <DialogDescription className="text-base pt-2">
                            Você está prestes a <strong>APAGAR TODOS OS DADOS</strong> do banco de dados (exceto admin).
                            <br /><br />
                            Esta ação é irreversível. Todas as vagas, candidaturas e empresas serão perdidas.
                        </DialogDescription>
                    </DialogHeader>
                    <DialogFooter className="gap-2 sm:gap-0">
                        <Button variant="ghost" onClick={() => setShowConfirmDialog(false)}>
                            Cancelar, me tire daqui!
                        </Button>
                        <Button
                            variant="destructive"
                            onClick={() => {
                                setShowConfirmDialog(false);
                                handleStream('reset', 'reset');
                            }}
                        >
                            Sim, apagar tudo
                        </Button>
                    </DialogFooter>
                </DialogContent>
            </Dialog>
        </div>
    );
}
