import React, { useState } from 'react';
import { Head, router } from '@inertiajs/react';
import { SEOHead } from '@/Components/SEOHead';
import {
    Server,
    Database,
    ShieldCheck,
    CheckCircle2,
    XCircle,
    AlertTriangle,
    ArrowRight,
    ArrowLeft,
    Eye,
    EyeOff,
    Lock,
    User,
    Mail,
    Globe,
    Cpu,
    Check,
    Sparkles,
    Loader2,
    RefreshCw
} from 'lucide-react';

interface Props {
    requirements: {
        php_version: string;
        php_satisfied: boolean;
        extensions: Record<string, boolean>;
        extensions_passed: boolean;
        permissions: Record<string, boolean>;
        permissions_passed: boolean;
        can_proceed: boolean;
    };
    defaultConfig: {
        app_name: string;
        app_url: string;
        db_driver: string;
        db_host: string;
        db_port: string;
        db_database: string;
        db_username: string;
        db_password: string;
        admin_name: string;
        admin_email: string;
        admin_password: string;
        editor_name: string;
        editor_email: string;
        editor_password: string;
    };
}

export default function Index({ requirements, defaultConfig }: Props) {
    const [step, setStep] = useState<number>(1);
    
    // Database Form State
    const [dbData, setDbData] = useState({
        app_name: defaultConfig.app_name,
        app_url: defaultConfig.app_url,
        db_driver: defaultConfig.db_driver,
        db_host: defaultConfig.db_host,
        db_port: defaultConfig.db_port,
        db_database: defaultConfig.db_database,
        db_username: defaultConfig.db_username,
        db_password: defaultConfig.db_password,
    });
    
    // Account Form State
    const [accountData, setAccountData] = useState({
        admin_name: defaultConfig.admin_name,
        admin_email: defaultConfig.admin_email,
        admin_password: defaultConfig.admin_password,
        editor_name: defaultConfig.editor_name,
        editor_email: defaultConfig.editor_email,
        editor_password: defaultConfig.editor_password,
    });

    // Password visibility toggles
    const [showDbPassword, setShowDbPassword] = useState(false);
    const [showAdminPassword, setShowAdminPassword] = useState(false);
    const [showEditorPassword, setShowEditorPassword] = useState(false);

    // Testing DB state
    const [testingDb, setTestingDb] = useState(false);
    const [dbTestResult, setDbTestResult] = useState<{ success: boolean; message: string } | null>(null);

    // Installation Progress State
    const [installing, setInstalling] = useState(false);
    const [installResult, setInstallResult] = useState<{ success: boolean; message: string } | null>(null);

    const handleTestDb = async () => {
        setTestingDb(true);
        setDbTestResult(null);

        try {
            const res = await fetch('/install/test-db', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                    'X-CSRF-TOKEN': (document.querySelector('meta[name="csrf-token"]') as HTMLMetaElement)?.content || '',
                },
                body: JSON.stringify({
                    driver: dbData.db_driver,
                    host: dbData.db_host,
                    port: dbData.db_port,
                    database: dbData.db_database,
                    username: dbData.db_username,
                    password: dbData.db_password,
                }),
            });

            const data = await res.json();
            setDbTestResult(data);
        } catch (err: any) {
            setDbTestResult({
                success: false,
                message: 'Failed to communicate with the server: ' + (err.message || 'Unknown network error'),
            });
        } finally {
            setTestingDb(false);
        }
    };

    const handleFinalInstall = async () => {
        setInstalling(true);
        setInstallResult(null);

        try {
            const res = await fetch('/install/process', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                    'X-CSRF-TOKEN': (document.querySelector('meta[name="csrf-token"]') as HTMLMetaElement)?.content || '',
                },
                body: JSON.stringify({
                    ...dbData,
                    ...accountData,
                }),
            });

            const data = await res.json();
            setInstallResult(data);
            if (data.success) {
                setStep(4);
            }
        } catch (err: any) {
            setInstallResult({
                success: false,
                message: 'Installation encountered an error: ' + (err.message || 'Unknown error'),
            });
        } finally {
            setInstalling(false);
        }
    };

    return (
        <div className="min-h-screen bg-[#060B18] text-white flex flex-col items-center justify-center p-4 sm:p-6 relative overflow-hidden font-sans selection:bg-[#00F2FE]/20 selection:text-[#00F2FE]">
            <SEOHead
                title="System Installation Wizard | Tech in Soul"
                description="Automated setup wizard for Tech in Soul Enterprise Software Suite."
            />

            {/* Background Ambient Glows */}
            <div className="absolute -top-40 -left-40 w-96 h-96 bg-[#00F2FE]/10 rounded-full blur-3xl pointer-events-none" />
            <div className="absolute -bottom-40 -right-40 w-96 h-96 bg-[#38BDF8]/10 rounded-full blur-3xl pointer-events-none" />

            <div className="w-full max-w-3xl z-10 my-8">
                {/* Header Branding */}
                <div className="text-center mb-8">
                    <div className="inline-flex items-center justify-center w-16 h-16 rounded-2xl bg-[#0B132B] border border-[#00F2FE]/30 shadow-[0_0_25px_rgba(0,242,254,0.15)] mb-4">
                        <Server className="w-8 h-8 text-[#00F2FE]" />
                    </div>
                    <h1 className="text-2xl sm:text-3xl font-extrabold tracking-tight">
                        TECH IN <span className="text-transparent bg-clip-text bg-gradient-to-r from-[#00F2FE] to-[#38BDF8]">SOUL</span>
                    </h1>
                    <p className="text-xs text-slate-400 mt-1 uppercase tracking-widest font-semibold">
                        Enterprise Software System Setup Wizard
                    </p>
                </div>

                {/* Step Navigation Bar */}
                <div className="grid grid-cols-4 gap-2 mb-6">
                    {[
                        { num: 1, title: 'Requirements', icon: Cpu },
                        { num: 2, title: 'Database', icon: Database },
                        { num: 3, title: 'Accounts', icon: ShieldCheck },
                        { num: 4, title: 'Complete', icon: Sparkles },
                    ].map((s) => {
                        const Icon = s.icon;
                        const isActive = step === s.num;
                        const isDone = step > s.num;

                        return (
                            <div
                                key={s.num}
                                className={`flex items-center gap-2 p-3 rounded-xl border transition-all ${
                                    isActive
                                        ? 'bg-[#0B132B] border-[#00F2FE] text-[#00F2FE] shadow-[0_0_15px_rgba(0,242,254,0.15)]'
                                        : isDone
                                        ? 'bg-[#0B132B]/60 border-emerald-500/40 text-emerald-400'
                                        : 'bg-[#0B132B]/20 border-slate-800 text-slate-500'
                                }`}
                            >
                                <div
                                    className={`w-7 h-7 rounded-lg flex items-center justify-center text-xs font-bold shrink-0 ${
                                        isActive
                                            ? 'bg-[#00F2FE] text-[#060B18]'
                                            : isDone
                                            ? 'bg-emerald-500 text-white'
                                            : 'bg-slate-800 text-slate-400'
                                    }`}
                                >
                                    {isDone ? <Check className="w-4 h-4" /> : s.num}
                                </div>
                                <span className="text-xs font-bold hidden sm:inline truncate">{s.title}</span>
                            </div>
                        );
                    })}
                </div>

                {/* Main Card Container */}
                <div className="bg-[#0B132B]/80 backdrop-blur-xl border border-slate-800 rounded-3xl p-6 sm:p-8 shadow-2xl relative">
                    {/* STEP 1: SERVER REQUIREMENTS & PERMISSIONS */}
                    {step === 1 && (
                        <div className="space-y-6">
                            <div>
                                <h2 className="text-lg font-bold text-white flex items-center gap-2">
                                    <Cpu className="w-5 h-5 text-[#00F2FE]" />
                                    Server Environment &amp; Requirements
                                </h2>
                                <p className="text-xs text-slate-400 mt-0.5">
                                    Verify your server satisfies the minimum PHP runtime and file permission criteria.
                                </p>
                            </div>

                            {/* PHP Version Check */}
                            <div className="p-4 rounded-2xl bg-[#060B18] border border-slate-800 flex items-center justify-between">
                                <div>
                                    <div className="text-xs font-bold text-white uppercase">PHP Engine Version</div>
                                    <div className="text-xs text-slate-400">Required: &gt;= 8.2.0 (Detected: {requirements.php_version})</div>
                                </div>
                                {requirements.php_satisfied ? (
                                    <span className="flex items-center gap-1.5 text-xs font-bold text-emerald-400 bg-emerald-500/10 px-3 py-1.5 rounded-xl border border-emerald-500/30">
                                        <CheckCircle2 className="w-4 h-4" /> Passed
                                    </span>
                                ) : (
                                    <span className="flex items-center gap-1.5 text-xs font-bold text-rose-400 bg-rose-500/10 px-3 py-1.5 rounded-xl border border-rose-500/30">
                                        <XCircle className="w-4 h-4" /> Upgrade Required
                                    </span>
                                )}
                            </div>

                            {/* PHP Extensions Grid */}
                            <div>
                                <h3 className="text-xs font-bold text-slate-300 uppercase tracking-wider mb-2">Required PHP Extensions</h3>
                                <div className="grid grid-cols-2 sm:grid-cols-3 gap-2">
                                    {Object.entries(requirements.extensions).map(([ext, status]) => (
                                        <div
                                            key={ext}
                                            className="p-2.5 rounded-xl bg-[#060B18] border border-slate-850 flex items-center justify-between text-xs"
                                        >
                                            <span className="font-mono text-slate-300 capitalize">{ext.replace('_', ' ')}</span>
                                            {status ? (
                                                <CheckCircle2 className="w-4 h-4 text-emerald-400 shrink-0" />
                                            ) : (
                                                <XCircle className="w-4 h-4 text-rose-400 shrink-0" />
                                            )}
                                        </div>
                                    ))}
                                </div>
                            </div>

                            {/* Folder Permissions */}
                            <div>
                                <h3 className="text-xs font-bold text-slate-300 uppercase tracking-wider mb-2">Directory Writable Permissions</h3>
                                <div className="grid grid-cols-1 sm:grid-cols-2 gap-2">
                                    {Object.entries(requirements.permissions).map(([pathKey, isWritable]) => (
                                        <div
                                            key={pathKey}
                                            className="p-2.5 rounded-xl bg-[#060B18] border border-slate-850 flex items-center justify-between text-xs"
                                        >
                                            <span className="font-mono text-slate-300">/{pathKey.replace('_', '/')}</span>
                                            {isWritable ? (
                                                <span className="text-[11px] font-bold text-emerald-400 bg-emerald-500/10 px-2 py-0.5 rounded border border-emerald-500/20">Writable</span>
                                            ) : (
                                                <span className="text-[11px] font-bold text-rose-400 bg-rose-500/10 px-2 py-0.5 rounded border border-rose-500/20">Unwritable</span>
                                            )}
                                        </div>
                                    ))}
                                </div>
                            </div>

                            {/* Next Button */}
                            <div className="pt-4 flex justify-end">
                                <button
                                    type="button"
                                    disabled={!requirements.can_proceed}
                                    onClick={() => setStep(2)}
                                    className={`px-6 py-3 rounded-xl text-xs font-bold flex items-center gap-2 transition-all ${
                                        requirements.can_proceed
                                            ? 'btn-aqua shadow-[0_0_20px_rgba(0,242,254,0.25)]'
                                            : 'bg-slate-800 text-slate-500 cursor-not-allowed'
                                    }`}
                                >
                                    Proceed to Database Setup <ArrowRight className="w-4 h-4" />
                                </button>
                            </div>
                        </div>
                    )}

                    {/* STEP 2: DATABASE CONFIGURATION */}
                    {step === 2 && (
                        <div className="space-y-6">
                            <div>
                                <h2 className="text-lg font-bold text-white flex items-center gap-2">
                                    <Database className="w-5 h-5 text-[#00F2FE]" />
                                    Database Connection Settings
                                </h2>
                                <p className="text-xs text-slate-400 mt-0.5">
                                    Enter your database server credentials. All credentials will be saved securely with double quotes in .env.
                                </p>
                            </div>

                            <div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
                                <div>
                                    <label className="text-xs font-bold text-slate-300 uppercase block mb-1">Application Name</label>
                                    <input
                                        type="text"
                                        value={dbData.app_name}
                                        onChange={(e) => setDbData({ ...dbData, app_name: e.target.value })}
                                        className="w-full bg-[#060B18] border border-slate-800 rounded-xl px-4 py-2.5 text-xs text-white focus:outline-none focus:border-[#00F2FE]"
                                    />
                                </div>
                                <div>
                                    <label className="text-xs font-bold text-slate-300 uppercase block mb-1">Application URL</label>
                                    <input
                                        type="url"
                                        value={dbData.app_url}
                                        onChange={(e) => setDbData({ ...dbData, app_url: e.target.value })}
                                        className="w-full bg-[#060B18] border border-slate-800 rounded-xl px-4 py-2.5 text-xs text-white focus:outline-none focus:border-[#00F2FE]"
                                    />
                                </div>
                            </div>

                            <div className="grid grid-cols-1 sm:grid-cols-3 gap-4">
                                <div>
                                    <label className="text-xs font-bold text-slate-300 uppercase block mb-1">Database Driver</label>
                                    <select
                                        value={dbData.db_driver}
                                        onChange={(e) => setDbData({ ...dbData, db_driver: e.target.value })}
                                        className="w-full bg-[#060B18] border border-slate-800 rounded-xl px-4 py-2.5 text-xs text-white focus:outline-none focus:border-[#00F2FE]"
                                    >
                                        <option value="mysql">MySQL / MariaDB</option>
                                        <option value="sqlite">SQLite</option>
                                        <option value="pgsql">PostgreSQL</option>
                                    </select>
                                </div>
                                <div>
                                    <label className="text-xs font-bold text-slate-300 uppercase block mb-1">Database Host</label>
                                    <input
                                        type="text"
                                        value={dbData.db_host}
                                        onChange={(e) => setDbData({ ...dbData, db_host: e.target.value })}
                                        placeholder="127.0.0.1"
                                        className="w-full bg-[#060B18] border border-slate-800 rounded-xl px-4 py-2.5 text-xs text-white focus:outline-none focus:border-[#00F2FE]"
                                    />
                                </div>
                                <div>
                                    <label className="text-xs font-bold text-slate-300 uppercase block mb-1">Database Port</label>
                                    <input
                                        type="text"
                                        value={dbData.db_port}
                                        onChange={(e) => setDbData({ ...dbData, db_port: e.target.value })}
                                        placeholder="3306"
                                        className="w-full bg-[#060B18] border border-slate-800 rounded-xl px-4 py-2.5 text-xs text-white focus:outline-none focus:border-[#00F2FE]"
                                    />
                                </div>
                            </div>

                            <div className="grid grid-cols-1 sm:grid-cols-3 gap-4">
                                <div>
                                    <label className="text-xs font-bold text-slate-300 uppercase block mb-1">Database Name *</label>
                                    <input
                                        type="text"
                                        value={dbData.db_database}
                                        onChange={(e) => setDbData({ ...dbData, db_database: e.target.value })}
                                        placeholder="techinsoul"
                                        className="w-full bg-[#060B18] border border-slate-800 rounded-xl px-4 py-2.5 text-xs text-white focus:outline-none focus:border-[#00F2FE]"
                                    />
                                </div>
                                <div>
                                    <label className="text-xs font-bold text-slate-300 uppercase block mb-1">Database Username</label>
                                    <input
                                        type="text"
                                        value={dbData.db_username}
                                        onChange={(e) => setDbData({ ...dbData, db_username: e.target.value })}
                                        placeholder="root"
                                        className="w-full bg-[#060B18] border border-slate-800 rounded-xl px-4 py-2.5 text-xs text-white focus:outline-none focus:border-[#00F2FE]"
                                    />
                                </div>
                                <div>
                                    <label className="text-xs font-bold text-slate-300 uppercase block mb-1">Database Password</label>
                                    <div className="relative">
                                        <input
                                            type={showDbPassword ? 'text' : 'password'}
                                            value={dbData.db_password}
                                            onChange={(e) => setDbData({ ...dbData, db_password: e.target.value })}
                                            placeholder="(leave blank if none)"
                                            className="w-full bg-[#060B18] border border-slate-800 rounded-xl px-4 py-2.5 pr-10 text-xs text-white focus:outline-none focus:border-[#00F2FE]"
                                        />
                                        <button
                                            type="button"
                                            onClick={() => setShowDbPassword(!showDbPassword)}
                                            className="absolute right-3 top-2.5 text-slate-400 hover:text-white transition-colors focus:outline-none"
                                            tabIndex={-1}
                                            aria-label={showDbPassword ? 'Hide password' : 'Show password'}
                                        >
                                            {showDbPassword ? <EyeOff className="w-4 h-4 text-[#00F2FE]" /> : <Eye className="w-4 h-4" />}
                                        </button>
                                    </div>
                                </div>
                            </div>

                            {/* Test Connection Button & Result */}
                            <div className="p-4 rounded-2xl bg-[#060B18] border border-slate-800 space-y-3">
                                <div className="flex items-center justify-between">
                                    <div>
                                        <div className="text-xs font-bold text-white">Live Connection Verification</div>
                                        <div className="text-[11px] text-slate-400">Test if MySQL database exists or can be created</div>
                                    </div>
                                    <button
                                        type="button"
                                        disabled={testingDb}
                                        onClick={handleTestDb}
                                        className="px-4 py-2 rounded-xl bg-slate-800 hover:bg-slate-700 text-xs font-bold text-[#00F2FE] border border-slate-700 flex items-center gap-1.5"
                                    >
                                        {testingDb ? <Loader2 className="w-3.5 h-3.5 animate-spin" /> : <RefreshCw className="w-3.5 h-3.5" />}
                                        Test DB Connection
                                    </button>
                                </div>

                                {dbTestResult && (
                                    <div
                                        className={`p-3 rounded-xl text-xs font-semibold flex items-center gap-2 ${
                                            dbTestResult.success
                                                ? 'bg-emerald-500/10 border border-emerald-500/30 text-emerald-400'
                                                : 'bg-rose-500/10 border border-rose-500/30 text-rose-400'
                                        }`}
                                    >
                                        {dbTestResult.success ? <CheckCircle2 className="w-4 h-4 shrink-0" /> : <XCircle className="w-4 h-4 shrink-0" />}
                                        <span>{dbTestResult.message}</span>
                                    </div>
                                )}
                            </div>

                            {/* Buttons */}
                            <div className="pt-4 flex items-center justify-between">
                                <button
                                    type="button"
                                    onClick={() => setStep(1)}
                                    className="px-4 py-2.5 rounded-xl border border-slate-800 text-xs font-bold text-slate-400 hover:text-white flex items-center gap-1.5"
                                >
                                    <ArrowLeft className="w-4 h-4" /> Back
                                </button>
                                <button
                                    type="button"
                                    onClick={() => setStep(3)}
                                    className="btn-aqua px-6 py-3 rounded-xl text-xs font-bold flex items-center gap-2 shadow-[0_0_20px_rgba(0,242,254,0.25)]"
                                >
                                    Proceed to Account Setup <ArrowRight className="w-4 h-4" />
                                </button>
                            </div>
                        </div>
                    )}

                    {/* STEP 3: SUPER ADMIN & EDITOR CREDENTIALS */}
                    {step === 3 && (
                        <div className="space-y-6">
                            <div>
                                <h2 className="text-lg font-bold text-white flex items-center gap-2">
                                    <ShieldCheck className="w-5 h-5 text-[#00F2FE]" />
                                    Admin &amp; Editor Account Credentials
                                </h2>
                                <p className="text-xs text-slate-400 mt-0.5">
                                    Configure Super Administrator and Content Editor accounts. All seeds and modules will be populated.
                                </p>
                            </div>

                            {/* Super Admin Section */}
                            <div className="p-4 rounded-2xl bg-[#060B18] border border-cyan-500/30 space-y-4">
                                <div className="flex items-center justify-between border-b border-slate-800 pb-2">
                                    <div className="flex items-center gap-2">
                                        <ShieldCheck className="w-4 h-4 text-[#00F2FE]" />
                                        <span className="text-xs font-bold text-white uppercase tracking-wider">Super Administrator (Full System Control)</span>
                                    </div>
                                    <span className="text-[10px] font-extrabold uppercase text-[#00F2FE] bg-[#00F2FE]/10 px-2.5 py-0.5 rounded-full border border-[#00F2FE]/30">
                                        Role: super_admin
                                    </span>
                                </div>

                                <div className="grid grid-cols-1 sm:grid-cols-3 gap-3">
                                    <div>
                                        <label className="text-[11px] font-bold text-slate-300 uppercase block mb-1">Full Name</label>
                                        <input
                                            type="text"
                                            value={accountData.admin_name}
                                            onChange={(e) => setAccountData({ ...accountData, admin_name: e.target.value })}
                                            className="w-full bg-[#0B132B] border border-slate-800 rounded-xl px-3.5 py-2 text-xs text-white focus:outline-none focus:border-[#00F2FE]"
                                        />
                                    </div>
                                    <div>
                                        <label className="text-[11px] font-bold text-slate-300 uppercase block mb-1">Admin Email *</label>
                                        <input
                                            type="email"
                                            value={accountData.admin_email}
                                            onChange={(e) => setAccountData({ ...accountData, admin_email: e.target.value })}
                                            className="w-full bg-[#0B132B] border border-slate-800 rounded-xl px-3.5 py-2 text-xs text-white focus:outline-none focus:border-[#00F2FE]"
                                        />
                                    </div>
                                    <div>
                                        <label className="text-[11px] font-bold text-slate-300 uppercase block mb-1">Admin Password *</label>
                                        <div className="relative">
                                            <input
                                                type={showAdminPassword ? 'text' : 'password'}
                                                value={accountData.admin_password}
                                                onChange={(e) => setAccountData({ ...accountData, admin_password: e.target.value })}
                                                className="w-full bg-[#0B132B] border border-slate-800 rounded-xl px-3.5 py-2 pr-10 text-xs text-white focus:outline-none focus:border-[#00F2FE]"
                                            />
                                            <button
                                                type="button"
                                                onClick={() => setShowAdminPassword(!showAdminPassword)}
                                                className="absolute right-3 top-2 text-slate-400 hover:text-white transition-colors focus:outline-none"
                                                tabIndex={-1}
                                                aria-label={showAdminPassword ? 'Hide password' : 'Show password'}
                                            >
                                                {showAdminPassword ? <EyeOff className="w-3.5 h-3.5 text-[#00F2FE]" /> : <Eye className="w-3.5 h-3.5" />}
                                            </button>
                                        </div>
                                    </div>
                                </div>
                            </div>

                            {/* Content Editor Section */}
                            <div className="p-4 rounded-2xl bg-[#060B18] border border-slate-800 space-y-4">
                                <div className="flex items-center justify-between border-b border-slate-800 pb-2">
                                    <div className="flex items-center gap-2">
                                        <User className="w-4 h-4 text-emerald-400" />
                                        <span className="text-xs font-bold text-white uppercase tracking-wider">Content Editor (Strict Content Access Only)</span>
                                    </div>
                                    <span className="text-[10px] font-extrabold uppercase text-emerald-400 bg-emerald-500/10 px-2.5 py-0.5 rounded-full border border-emerald-500/30">
                                        Role: editor
                                    </span>
                                </div>

                                <div className="grid grid-cols-1 sm:grid-cols-3 gap-3">
                                    <div>
                                        <label className="text-[11px] font-bold text-slate-300 uppercase block mb-1">Full Name</label>
                                        <input
                                            type="text"
                                            value={accountData.editor_name}
                                            onChange={(e) => setAccountData({ ...accountData, editor_name: e.target.value })}
                                            className="w-full bg-[#0B132B] border border-slate-800 rounded-xl px-3.5 py-2 text-xs text-white focus:outline-none focus:border-[#00F2FE]"
                                        />
                                    </div>
                                    <div>
                                        <label className="text-[11px] font-bold text-slate-300 uppercase block mb-1">Editor Email *</label>
                                        <input
                                            type="email"
                                            value={accountData.editor_email}
                                            onChange={(e) => setAccountData({ ...accountData, editor_email: e.target.value })}
                                            className="w-full bg-[#0B132B] border border-slate-800 rounded-xl px-3.5 py-2 text-xs text-white focus:outline-none focus:border-[#00F2FE]"
                                        />
                                    </div>
                                    <div>
                                        <label className="text-[11px] font-bold text-slate-300 uppercase block mb-1">Editor Password *</label>
                                        <div className="relative">
                                            <input
                                                type={showEditorPassword ? 'text' : 'password'}
                                                value={accountData.editor_password}
                                                onChange={(e) => setAccountData({ ...accountData, editor_password: e.target.value })}
                                                className="w-full bg-[#0B132B] border border-slate-800 rounded-xl px-3.5 py-2 pr-10 text-xs text-white focus:outline-none focus:border-[#00F2FE]"
                                            />
                                            <button
                                                type="button"
                                                onClick={() => setShowEditorPassword(!showEditorPassword)}
                                                className="absolute right-3 top-2 text-slate-400 hover:text-white transition-colors focus:outline-none"
                                                tabIndex={-1}
                                                aria-label={showEditorPassword ? 'Hide password' : 'Show password'}
                                            >
                                                {showEditorPassword ? <EyeOff className="w-3.5 h-3.5 text-[#00F2FE]" /> : <Eye className="w-3.5 h-3.5" />}
                                            </button>
                                        </div>
                                    </div>
                                </div>
                            </div>

                            {installResult && !installResult.success && (
                                <div className="p-3.5 rounded-xl bg-rose-500/10 border border-rose-500/30 text-rose-400 text-xs font-semibold flex items-center gap-2">
                                    <XCircle className="w-4 h-4 shrink-0" />
                                    <span>{installResult.message}</span>
                                </div>
                            )}

                            {/* Buttons */}
                            <div className="pt-4 flex items-center justify-between">
                                <button
                                    type="button"
                                    onClick={() => setStep(2)}
                                    disabled={installing}
                                    className="px-4 py-2.5 rounded-xl border border-slate-800 text-xs font-bold text-slate-400 hover:text-white flex items-center gap-1.5"
                                >
                                    <ArrowLeft className="w-4 h-4" /> Back
                                </button>
                                <button
                                    type="button"
                                    disabled={installing}
                                    onClick={handleFinalInstall}
                                    className="btn-aqua px-8 py-3.5 rounded-xl text-xs font-bold flex items-center gap-2 shadow-[0_0_25px_rgba(0,242,254,0.35)]"
                                >
                                    {installing ? (
                                        <>
                                            <Loader2 className="w-4 h-4 animate-spin" />
                                            Running Migrations &amp; Initializing Data...
                                        </>
                                    ) : (
                                        <>
                                            <Sparkles className="w-4 h-4" />
                                            Execute Installation &amp; Seed Database
                                        </>
                                    )}
                                </button>
                            </div>
                        </div>
                    )}

                    {/* STEP 4: INSTALLATION COMPLETED */}
                    {step === 4 && (
                        <div className="text-center py-6 space-y-6">
                            <div className="w-20 h-20 rounded-3xl bg-emerald-500/10 border border-emerald-500/30 flex items-center justify-center mx-auto text-emerald-400 shadow-[0_0_30px_rgba(16,185,129,0.2)]">
                                <CheckCircle2 className="w-10 h-10" />
                            </div>

                            <div className="space-y-2">
                                <h2 className="text-2xl font-extrabold text-white">
                                    Installation Completed Successfully!
                                </h2>
                                <p className="text-xs text-slate-400 max-w-md mx-auto">
                                    Tech in Soul enterprise suite has been initialized. All migrations, database tables, settings, content modules, and administrator roles are ready.
                                </p>
                            </div>

                            {/* Summary Box */}
                            <div className="p-5 rounded-2xl bg-[#060B18] border border-slate-800 text-left max-w-md mx-auto space-y-3">
                                <div className="text-xs font-bold text-slate-300 uppercase tracking-wider border-b border-slate-800 pb-2">
                                    Admin Login Details
                                </div>
                                <div className="space-y-1.5 text-xs">
                                    <div className="flex justify-between">
                                        <span className="text-slate-400">Super Admin Email:</span>
                                        <span className="font-mono text-[#00F2FE] font-bold">{accountData.admin_email}</span>
                                    </div>
                                    <div className="flex justify-between">
                                        <span className="text-slate-400">Editor Email:</span>
                                        <span className="font-mono text-emerald-400 font-bold">{accountData.editor_email}</span>
                                    </div>
                                    <div className="flex justify-between">
                                        <span className="text-slate-400">Database Engine:</span>
                                        <span className="font-mono text-slate-300">{dbData.db_driver.toUpperCase()} ({dbData.db_database})</span>
                                    </div>
                                </div>
                            </div>

                            <div className="pt-2">
                                <a
                                    href="/login"
                                    className="btn-aqua inline-flex items-center gap-2 px-8 py-3.5 rounded-xl text-xs font-bold shadow-[0_0_25px_rgba(0,242,254,0.35)]"
                                >
                                    Log In to Admin Dashboard <ArrowRight className="w-4 h-4" />
                                </a>
                            </div>
                        </div>
                    )}
                </div>
            </div>
        </div>
    );
}
