import React, { useState } from 'react';
import { Database, Terminal, Play, CheckCircle, ArrowLeft } from 'lucide-react';
import { HybridBackend } from '../services/backend.ts';

export const UpdateDbView: React.FC = () => {
    const [installing, setInstalling] = useState(false);
    const [installLogs, setInstallLogs] = useState<string[]>([]);
    const [finished, setFinished] = useState(false);

    const runInstallScript = async () => {
        setInstalling(true);
        setInstallLogs([]);
        setFinished(false);
        
        // Simula a execução do script sh/update_db.sh
        await HybridBackend.runInstallScript((log) => {
            setInstallLogs(prev => [...prev, log]);
        });
        
        setFinished(true);
        setInstalling(false);
    };

    const handleGoBack = () => {
        window.location.href = './'; // Volta para a raiz
    };

    return (
        <div className="min-h-screen bg-gray-900 flex items-center justify-center p-4">
            <div className="w-full max-w-2xl bg-white rounded-xl shadow-2xl overflow-hidden">
                <div className="bg-gray-100 p-6 border-b border-gray-200 flex items-center justify-between">
                    <div className="flex items-center gap-4">
                        <div className="w-12 h-12 bg-blue-600 rounded-lg flex items-center justify-center text-white">
                            <Database size={24} />
                        </div>
                        <div>
                            <h1 className="text-xl font-bold text-gray-900 uppercase">SCOREODONTO ADMIN</h1>
                            <p className="text-gray-500 text-xs font-bold uppercase">FERRAMENTA DE ATUALIZAÇÃO DE BANCO</p>
                        </div>
                    </div>
                    <button onClick={handleGoBack} className="text-gray-500 hover:text-gray-800 flex items-center gap-1 text-xs font-bold uppercase">
                        <ArrowLeft size={16}/> VOLTAR AO SISTEMA
                    </button>
                </div>
                
                <div className="p-8">
                    {!installing && installLogs.length === 0 ? (
                        <div className="text-center space-y-6">
                            <div className="w-20 h-20 bg-amber-100 text-amber-600 rounded-full flex items-center justify-center mx-auto">
                                <Terminal size={40} />
                            </div>
                            <div>
                                <h2 className="text-lg font-bold text-gray-800 uppercase">SCRIPT DE ATUALIZAÇÃO (SH/UPDATE_DB.SH)</h2>
                                <p className="text-gray-500 text-sm mt-2 max-w-md mx-auto uppercase">
                                    ESTA AÇÃO IRÁ LER A PLANILHA "DADOS PACIENTES", GERAR UM BACKUP SQL E ATUALIZAR AS TABELAS DO POSTGRESQL.
                                </p>
                            </div>
                            <div className="bg-gray-800 text-green-400 p-4 rounded-lg font-mono text-sm text-left max-w-md mx-auto shadow-inner">
                                $ ./sh/update_db.sh --force-sync
                            </div>
                            <button 
                                onClick={runInstallScript}
                                className="bg-blue-600 hover:bg-blue-700 text-white px-8 py-4 rounded-lg font-bold uppercase flex items-center gap-3 mx-auto transition-all hover:scale-105 shadow-lg"
                            >
                                <Play size={20} fill="currentColor" />
                                EXECUTAR ATUALIZAÇÃO
                            </button>
                        </div>
                    ) : (
                        <div className="space-y-4">
                            <div className="flex justify-between items-center mb-2">
                                <h3 className="font-bold text-gray-800 uppercase flex items-center gap-2">
                                    <Terminal size={18} /> TERMINAL DE SAÍDA
                                </h3>
                                {finished && (
                                    <span className="text-green-600 text-xs font-bold uppercase flex items-center gap-1">
                                        <CheckCircle size={14} /> PROCESSO FINALIZADO
                                    </span>
                                )}
                            </div>
                            <div className="bg-gray-900 text-green-500 font-mono text-xs p-6 rounded-lg h-80 overflow-y-auto shadow-inner border-4 border-gray-800">
                                {installLogs.map((log, i) => (
                                    <div key={i} className="mb-1">{log}</div>
                                ))}
                                {installing && (
                                    <div className="animate-pulse mt-2">_</div>
                                )}
                            </div>
                            {finished && (
                                <button 
                                    onClick={handleGoBack}
                                    className="w-full py-3 bg-gray-200 hover:bg-gray-300 text-gray-800 font-bold rounded-lg uppercase transition-colors"
                                >
                                    VOLTAR PARA O LOGIN
                                </button>
                            )}
                        </div>
                    )}
                </div>
            </div>
        </div>
    );
};