import { useState, useRef, useEffect } from 'react';
import { Card, CardContent, CardHeader, CardTitle, CardDescription } from '@/components/ui/card';
import { Button } from '@/components/ui/button';
import { Terminal, Download, Upload, FileText, AlertCircle, RefreshCw } from 'lucide-react';
import { toast } from 'sonner';

export function SeccionSistema() {
  const [mongoshCommand, setMongoshCommand] = useState('');
  const [consoleHistory, setConsoleHistory] = useState<{ id: number; type: 'input' | 'output' | 'error'; content: string }[]>([]);
  const [logs, setLogs] = useState<string>('');
  const [isLogsModalOpen, setIsLogsModalOpen] = useState(false);
  const [isExecuting, setIsExecuting] = useState(false);
  const historyCounter = useRef(0);
  const consoleEndRef = useRef<HTMLDivElement>(null);
  const terminalContainerRef = useRef<HTMLDivElement>(null);
  const inputRef = useRef<HTMLInputElement>(null);
  const commandHistoryRef = useRef<string[]>([]);
  const historyIndexRef = useRef<number>(-1);

  const scrollToBottom = () => {
    if (terminalContainerRef.current) {
      terminalContainerRef.current.scrollTop = terminalContainerRef.current.scrollHeight;
    }
  };

  useEffect(() => {
    scrollToBottom();
  }, [consoleHistory, mongoshCommand]);

  const addHistory = (type: 'input' | 'output' | 'error', content: string) => {
    setConsoleHistory(prev => [...prev, { id: historyCounter.current++, type, content }]);
  };

  const handleExecuteMongosh = async () => {
    if (!mongoshCommand.trim()) return;
    
    const commandToRun = mongoshCommand;
    addHistory('input', commandToRun);
    
    if (commandHistoryRef.current[commandHistoryRef.current.length - 1] !== commandToRun) {
      commandHistoryRef.current.push(commandToRun);
    }
    historyIndexRef.current = commandHistoryRef.current.length;
    
    setMongoshCommand('');
    setIsExecuting(true);
    
    try {
      const response = await fetch('/api/admin/mongosh', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ command: commandToRun })
      });
      
      const data = await response.json();
      
      if (!response.ok) {
        addHistory('error', data.error || 'Error desconocido');
      } else {
        const outputString = typeof data.result === 'object' ? JSON.stringify(data.result, null, 2) : String(data.result);
        addHistory('output', outputString);
        if (data.isMemStore) {
          toast.warning('MongoDB no está conectado. Utilizando modo memoria.');
        }
      }
    } catch (error) {
      addHistory('error', String(error));
    } finally {
      setIsExecuting(false);
    }
  };

  const handleKeyDown = (e: React.KeyboardEvent<HTMLInputElement>) => {
    if (e.key === 'Enter') {
      e.preventDefault();
      handleExecuteMongosh();
    } else if (e.key === 'ArrowUp') {
      e.preventDefault();
      if (historyIndexRef.current > 0) {
        const newIndex = historyIndexRef.current - 1;
        historyIndexRef.current = newIndex;
        setMongoshCommand(commandHistoryRef.current[newIndex]);
      }
    } else if (e.key === 'ArrowDown') {
      e.preventDefault();
      if (historyIndexRef.current < commandHistoryRef.current.length - 1) {
        const newIndex = historyIndexRef.current + 1;
        historyIndexRef.current = newIndex;
        setMongoshCommand(commandHistoryRef.current[newIndex]);
      } else if (historyIndexRef.current === commandHistoryRef.current.length - 1) {
        historyIndexRef.current = commandHistoryRef.current.length;
        setMongoshCommand('');
      }
    }
  };

  const handleViewLogs = async () => {
    try {
      const response = await fetch('/api/admin/logs');
      if (!response.ok) throw new Error('Error al obtener logs');
      const data = await response.text();
      setLogs(data || 'No hay logs disponibles.');
      setIsLogsModalOpen(true);
    } catch (e) {
      toast.error('Error al cargar logs: ' + String(e));
    }
  };

  const handleExportData = () => {
    window.location.href = '/api/admin/db/export';
    toast.success('Descarga iniciada');
  };

  const handleImportData = (e: React.ChangeEvent<HTMLInputElement>) => {
    const file = e.target.files?.[0];
    if (!file) return;

    const reader = new FileReader();
    reader.onload = async (event) => {
      try {
        const content = event.target?.result as string;
        const dump = JSON.parse(content);
        
        const response = await fetch('/api/admin/db/import', {
          method: 'POST',
          headers: { 'Content-Type': 'application/json' },
          body: JSON.stringify(dump)
        });
        
        if (!response.ok) {
          const data = await response.json();
          throw new Error(data.error || 'Error al importar base de datos');
        }
        
        toast.success('Base de datos importada exitosamente. Recarga la página para ver los cambios.');
        // Opcional: window.location.reload();
      } catch (error) {
        toast.error('Error: ' + String(error));
      }
    };
    reader.readAsText(file);
    e.target.value = ''; // Reset input
  };

  const handleClearConsole = () => {
    setConsoleHistory([]);
  };

  return (
    <div className="space-y-6">
      <div className="flex items-center justify-between">
        <div>
          <h2 className="text-3xl font-bold tracking-tight text-gray-900 dark:text-white">Sistema y Depuración</h2>
          <p className="text-gray-500 dark:text-gray-400">Herramientas avanzadas para administradores</p>
        </div>
      </div>

      <div className="grid grid-cols-1 md:grid-cols-3 gap-6">
        <Card className="col-span-1 md:col-span-3">
          <CardHeader>
            <div className="flex items-center justify-between">
              <div>
                <CardTitle className="flex items-center gap-2">
                  <Terminal className="h-5 w-5" /> Consola mongosh
                </CardTitle>
                <CardDescription>Ejecuta comandos de consulta directamente en la base de datos.</CardDescription>
              </div>
              <Button variant="outline" size="sm" onClick={handleClearConsole}>
                <RefreshCw className="h-4 w-4 mr-2" /> Limpiar
              </Button>
            </div>
          </CardHeader>
          <CardContent>
            <div 
              ref={terminalContainerRef}
              className="bg-gray-900 text-green-400 font-mono text-sm p-4 rounded-md h-[400px] overflow-y-auto flex flex-col gap-1 relative cursor-text group"
              onClick={() => inputRef.current?.focus({ preventScroll: true })}
            >
              {consoleHistory.length === 0 && (
                <div className="text-gray-500 italic mb-2">Conectado. Esperando comandos... Ej: db.pacientes.find()</div>
              )}
              {consoleHistory.map((item) => (
                <div key={item.id} className={`break-words ${item.type === 'error' ? 'text-red-400' : item.type === 'input' ? 'text-blue-300' : 'text-gray-300'}`}>
                  {item.type === 'input' && <span className="text-blue-500 mr-2">{'>'}</span>}
                  {item.type === 'output' && <span className="text-gray-500 mr-2">{'<-'}</span>}
                  {item.type === 'error' && <span className="text-red-500 mr-2">{'!'}</span>}
                  <pre className="inline whitespace-pre-wrap font-inherit m-0">{item.content}</pre>
                </div>
              ))}
              
              <div className="flex items-center text-blue-300 mt-1">
                <span className="text-blue-500 mr-2">{'>'}</span>
                <span className="whitespace-pre-wrap break-all">{mongoshCommand}</span>
                <span className="w-2 bg-green-400 animate-pulse ml-[1px] inline-block h-4 opacity-0 group-focus-within:opacity-100 transition-opacity"></span>
              </div>
              
              <div ref={consoleEndRef} className="h-1" />
              
              <input
                ref={inputRef}
                type="text"
                className="opacity-0 w-[1px] h-[1px] absolute overflow-hidden p-0 m-0 border-0 pointer-events-none"
                value={mongoshCommand}
                onChange={(e) => setMongoshCommand(e.target.value)}
                onKeyDown={handleKeyDown}
                disabled={isExecuting}
                autoComplete="off"
                spellCheck="false"
              />
            </div>
            
            <div className="mt-2 text-xs text-gray-500 flex items-center gap-1">
              <AlertCircle className="h-3 w-3" />
              Soporta asincronía. Variables globales: `db`, `ObjectId`. Flechas arriba/abajo para navegar el historial.
            </div>
          </CardContent>
        </Card>

        <Card>
          <CardHeader>
            <CardTitle className="flex items-center gap-2">
              <FileText className="h-5 w-5" /> Logs del Servidor
            </CardTitle>
            <CardDescription>Visualiza los registros recientes del servidor.</CardDescription>
          </CardHeader>
          <CardContent>
            <Button className="w-full" onClick={handleViewLogs}>
              Ver Logs Recientes
            </Button>
          </CardContent>
        </Card>

        <Card>
          <CardHeader>
            <CardTitle className="flex items-center gap-2">
              <Download className="h-5 w-5" /> Exportar Datos
            </CardTitle>
            <CardDescription>Descarga una copia completa de la base de datos (JSON).</CardDescription>
          </CardHeader>
          <CardContent>
            <Button className="w-full" variant="secondary" onClick={handleExportData}>
              Exportar Todo
            </Button>
          </CardContent>
        </Card>

        <Card>
          <CardHeader>
            <CardTitle className="flex items-center gap-2">
              <Upload className="h-5 w-5" /> Importar Datos
            </CardTitle>
            <CardDescription>Restaura la base de datos desde un archivo (JSON).</CardDescription>
          </CardHeader>
          <CardContent>
            <div className="relative">
              <input
                type="file"
                accept=".json"
                className="absolute inset-0 w-full h-full opacity-0 cursor-pointer"
                onChange={handleImportData}
              />
              <Button className="w-full" variant="destructive">
                Seleccionar e Importar
              </Button>
            </div>
            <p className="text-xs text-red-500 mt-2 text-center">Advertencia: Esto sobreescribirá todos los datos actuales.</p>
          </CardContent>
        </Card>
      </div>

      {isLogsModalOpen && (
        <div className="fixed inset-0 z-50 flex items-center justify-center bg-black bg-opacity-50">
          <div className="bg-white dark:bg-gray-900 rounded-lg p-6 w-full max-w-4xl max-h-[90vh] flex flex-col shadow-xl">
            <h3 className="text-lg font-bold mb-4 flex justify-between items-center text-gray-900 dark:text-white">
              <span>Logs del Servidor</span>
              <Button variant="ghost" size="sm" onClick={() => setIsLogsModalOpen(false)}>Cerrar</Button>
            </h3>
            <div className="flex-1 overflow-auto bg-gray-950 text-green-400 font-mono text-xs p-4 rounded border border-gray-800">
              <pre className="whitespace-pre-wrap">{logs}</pre>
            </div>
            <div className="mt-4 flex justify-end">
              <Button onClick={() => setIsLogsModalOpen(false)}>Aceptar</Button>
            </div>
          </div>
        </div>
      )}
    </div>
  );
}
