"use client";

import React, { useState, useEffect } from "react";
import {
  Wand2,
  CheckCircle2,
  AlertCircle,
  Database,
  Sliders,
  UserCheck,
  ShieldCheck,
  Lock,
  ArrowRight,
  ArrowLeft,
  RotateCw,
  ExternalLink,
} from "lucide-react";

export const InstallerWizardView: React.FC = () => {
  const [step, setStep] = useState(1);
  const [isLocked, setIsLocked] = useState(false);
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState("");
  const [dbTestMessage, setDbTestMessage] = useState("");

  // Installer State
  const [dbHost, setDbHost] = useState("127.0.0.1");
  const [dbPort, setDbPort] = useState("3306");
  const [dbName, setDbName] = useState("appointment_serial_db");
  const [dbUser, setDbUser] = useState("root");
  const [dbPass, setDbPass] = useState("");

  const [appName, setAppName] = useState("Auto Appointment Serial Management System");
  const [timezone, setTimezone] = useState("Asia/Dhaka");
  const [appUrl, setAppUrl] = useState("http://210.4.73.10:52/appointments/apps/appointment/1460/13030");
  const [startTime, setStartTime] = useState("07:05");
  const [totalSerials, setTotalSerials] = useState("5");
  const [intervalSeconds, setIntervalSeconds] = useState("60");

  const [adminName, setAdminName] = useState("System Administrator");
  const [adminEmail, setAdminEmail] = useState("admin@hospital-serial.com");
  const [adminUsername, setAdminUsername] = useState("admin");
  const [adminPassword, setAdminPassword] = useState("admin123");
  const [confirmPassword, setConfirmPassword] = useState("admin123");

  useEffect(() => {
    fetch("/api/installer")
      .then((res) => res.json())
      .then((data) => {
        if (data.isInstalled) {
          setIsLocked(true);
        }
      })
      .catch(() => {});
  }, []);

  const handleTestDb = async () => {
    setLoading(true);
    setDbTestMessage("");
    setError("");
    try {
      const res = await fetch("/api/installer", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({
          step: "test_db",
          dbHost,
          dbName,
          dbUser,
        }),
      });
      const data = await res.json();
      if (data.success) {
        setDbTestMessage("✓ " + data.message);
      } else {
        setError(data.error);
      }
    } catch (e) {
      setError("Failed to test connection");
    } finally {
      setLoading(false);
    }
  };

  const handleExecuteInstall = async () => {
    if (adminPassword !== confirmPassword) {
      setError("Passwords do not match");
      return;
    }

    setLoading(true);
    setError("");
    try {
      const res = await fetch("/api/installer", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({
          step: "execute_install",
          dbHost,
          dbName,
          dbUser,
          startTime,
          totalSerials,
          intervalSeconds,
          timezone,
          appUrl,
          adminName,
          adminEmail,
          adminUsername,
          adminPassword,
        }),
      });

      const data = await res.json();
      if (!res.ok || !data.success) throw new Error(data.error || "Installation failed");

      setStep(6);
      setIsLocked(true);
    } catch (err: unknown) {
      const msg = err instanceof Error ? err.message : "Error";
      setError(msg);
    } finally {
      setLoading(false);
    }
  };

  const handleUnlockDemo = async () => {
    await fetch("/api/installer", {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({ step: "unlock_for_demo" }),
    });
    setIsLocked(false);
    setStep(1);
  };

  if (isLocked && step !== 6) {
    return (
      <div className="max-w-2xl mx-auto p-8 rounded-2xl bg-slate-900 border border-slate-800 shadow-2xl text-center space-y-4">
        <div className="w-16 h-16 rounded-2xl bg-emerald-500/10 text-emerald-400 flex items-center justify-center mx-auto">
          <Lock className="w-8 h-8" />
        </div>
        <h2 className="text-2xl font-extrabold text-white">Installation is Already Completed</h2>
        <p className="text-xs text-slate-400 max-w-md mx-auto leading-relaxed">
          The security lockfile <code className="text-emerald-400 font-mono">install/installed.lock</code> is present. To access the control panel, visit the login page.
        </p>
        <div className="pt-4 flex items-center justify-center gap-3">
          <a
            href="/"
            className="px-6 py-2.5 bg-blue-600 hover:bg-blue-500 text-white rounded-xl text-xs font-bold transition-all"
          >
            Go to Admin Dashboard
          </a>
          <button
            onClick={handleUnlockDemo}
            className="px-4 py-2.5 bg-slate-800 hover:bg-slate-700 text-slate-300 rounded-xl text-xs font-semibold"
          >
            Re-run Wizard (Preview Mode)
          </button>
        </div>
      </div>
    );
  }

  return (
    <div className="max-w-3xl mx-auto rounded-2xl bg-slate-900 border border-slate-800 shadow-2xl overflow-hidden">
      {/* Wizard Header */}
      <div className="p-6 bg-gradient-to-r from-blue-900 via-indigo-950 to-slate-900 border-b border-slate-800 text-white flex flex-col sm:flex-row items-start sm:items-center justify-between gap-4">
        <div>
          <div className="inline-flex items-center gap-2 px-3 py-1 rounded-full bg-blue-500/20 text-blue-300 text-xs font-bold mb-2">
            <Wand2 className="w-3.5 h-3.5" />
            <span>STEP {step} OF 6</span>
          </div>
          <h2 className="text-xl font-extrabold">Web Installation Wizard</h2>
          <p className="text-xs text-slate-300 mt-0.5">Automated cPanel &amp; VPS MySQL Provisioning</p>
        </div>

        {/* Step Progress Pills */}
        <div className="flex items-center gap-1.5 bg-slate-950/60 p-1.5 rounded-xl border border-slate-800">
          {[1, 2, 3, 4, 5, 6].map((st) => (
            <div
              key={st}
              className={`w-7 h-7 rounded-lg text-xs font-bold flex items-center justify-center transition-all ${
                step === st
                  ? "bg-blue-600 text-white"
                  : step > st
                  ? "bg-emerald-500/20 text-emerald-400"
                  : "text-slate-600"
              }`}
            >
              {step > st ? "✓" : st}
            </div>
          ))}
        </div>
      </div>

      {/* Body */}
      <div className="p-8">
        {error && (
          <div className="mb-6 p-4 rounded-xl bg-rose-950/40 border border-rose-800/50 text-rose-300 text-xs font-semibold flex items-center gap-2">
            <AlertCircle className="w-4 h-4 text-rose-400 shrink-0" />
            <span>{error}</span>
          </div>
        )}

        {/* STEP 1: Requirements */}
        {step === 1 && (
          <div className="space-y-4">
            <h3 className="text-sm font-bold text-white">Step 1: System Requirements Verification</h3>
            <div className="space-y-2 border border-slate-800 rounded-xl p-4 bg-slate-950/50 text-xs">
              <div className="flex items-center justify-between py-1.5 border-b border-slate-800">
                <span className="text-slate-300 font-medium">PHP Version (&gt;= 8.0.0)</span>
                <span className="text-emerald-400 font-bold">PHP 8.2.0 ✓ PASS</span>
              </div>
              <div className="flex items-center justify-between py-1.5 border-b border-slate-800">
                <span className="text-slate-300 font-medium">PDO MySQL Extension</span>
                <span className="text-emerald-400 font-bold">Installed ✓ PASS</span>
              </div>
              <div className="flex items-center justify-between py-1.5 border-b border-slate-800">
                <span className="text-slate-300 font-medium">cURL &amp; OpenSSL Extensions</span>
                <span className="text-emerald-400 font-bold">Enabled ✓ PASS</span>
              </div>
              <div className="flex items-center justify-between py-1.5">
                <span className="text-slate-300 font-medium">Writable Storage Directory (logs/screenshots)</span>
                <span className="text-emerald-400 font-bold">Writable (0755) ✓ PASS</span>
              </div>
            </div>

            <div className="pt-4 flex justify-end">
              <button
                onClick={() => setStep(2)}
                className="px-6 py-2.5 bg-blue-600 hover:bg-blue-500 text-white rounded-xl text-xs font-bold flex items-center gap-2"
              >
                <span>Continue to Database Setup</span>
                <ArrowRight className="w-4 h-4" />
              </button>
            </div>
          </div>
        )}

        {/* STEP 2: Database */}
        {step === 2 && (
          <div className="space-y-4">
            <h3 className="text-sm font-bold text-white">Step 2: Database Credentials</h3>
            <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
              <div>
                <label className="block text-xs font-semibold text-slate-300 mb-1">Database Host</label>
                <input
                  type="text"
                  value={dbHost}
                  onChange={(e) => setDbHost(e.target.value)}
                  className="w-full px-3 py-2 bg-slate-950 border border-slate-700 rounded-xl text-xs text-white"
                />
              </div>
              <div>
                <label className="block text-xs font-semibold text-slate-300 mb-1">Database Port</label>
                <input
                  type="text"
                  value={dbPort}
                  onChange={(e) => setDbPort(e.target.value)}
                  className="w-full px-3 py-2 bg-slate-950 border border-slate-700 rounded-xl text-xs text-white"
                />
              </div>
              <div>
                <label className="block text-xs font-semibold text-slate-300 mb-1">Database Name</label>
                <input
                  type="text"
                  value={dbName}
                  onChange={(e) => setDbName(e.target.value)}
                  className="w-full px-3 py-2 bg-slate-950 border border-slate-700 rounded-xl text-xs text-white"
                />
              </div>
              <div>
                <label className="block text-xs font-semibold text-slate-300 mb-1">Database Username</label>
                <input
                  type="text"
                  value={dbUser}
                  onChange={(e) => setDbUser(e.target.value)}
                  className="w-full px-3 py-2 bg-slate-950 border border-slate-700 rounded-xl text-xs text-white"
                />
              </div>
              <div className="md:col-span-2">
                <label className="block text-xs font-semibold text-slate-300 mb-1">Database Password</label>
                <input
                  type="password"
                  value={dbPass}
                  onChange={(e) => setDbPass(e.target.value)}
                  placeholder="••••••••"
                  className="w-full px-3 py-2 bg-slate-950 border border-slate-700 rounded-xl text-xs text-white"
                />
              </div>
            </div>

            {dbTestMessage && (
              <p className="p-3 rounded-xl bg-emerald-950/40 border border-emerald-800/40 text-emerald-400 text-xs font-semibold">
                {dbTestMessage}
              </p>
            )}

            <div className="pt-4 flex items-center justify-between">
              <button
                type="button"
                onClick={handleTestDb}
                className="px-4 py-2 bg-slate-800 hover:bg-slate-700 text-slate-300 rounded-xl text-xs font-semibold flex items-center gap-1.5"
              >
                <RotateCw className={`w-3.5 h-3.5 ${loading ? "animate-spin" : ""}`} />
                <span>Test DB Connection</span>
              </button>

              <div className="flex gap-3">
                <button
                  onClick={() => setStep(1)}
                  className="px-4 py-2 bg-slate-800 hover:bg-slate-700 text-slate-300 rounded-xl text-xs font-semibold"
                >
                  Back
                </button>
                <button
                  onClick={() => setStep(3)}
                  className="px-6 py-2 bg-blue-600 hover:bg-blue-500 text-white rounded-xl text-xs font-bold"
                >
                  Continue
                </button>
              </div>
            </div>
          </div>
        )}

        {/* STEP 3: Settings */}
        {step === 3 && (
          <div className="space-y-4">
            <h3 className="text-sm font-bold text-white">Step 3: Daily Serial Defaults</h3>
            <div className="space-y-3">
              <div>
                <label className="block text-xs font-semibold text-slate-300 mb-1">External Appointment URL</label>
                <input
                  type="url"
                  value={appUrl}
                  onChange={(e) => setAppUrl(e.target.value)}
                  className="w-full px-3 py-2 bg-slate-950 border border-slate-700 rounded-xl text-xs text-white font-mono"
                />
              </div>

              <div className="grid grid-cols-1 md:grid-cols-3 gap-3">
                <div>
                  <label className="block text-xs font-semibold text-slate-300 mb-1">Start Time (Asia/Dhaka)</label>
                  <input
                    type="text"
                    value={startTime}
                    onChange={(e) => setStartTime(e.target.value)}
                    className="w-full px-3 py-2 bg-slate-950 border border-slate-700 rounded-xl text-xs text-white font-mono font-bold"
                  />
                </div>
                <div>
                  <label className="block text-xs font-semibold text-slate-300 mb-1">Total Serials</label>
                  <input
                    type="number"
                    value={totalSerials}
                    onChange={(e) => setTotalSerials(e.target.value)}
                    className="w-full px-3 py-2 bg-slate-950 border border-slate-700 rounded-xl text-xs text-white font-mono font-bold"
                  />
                </div>
                <div>
                  <label className="block text-xs font-semibold text-slate-300 mb-1">Interval (Seconds)</label>
                  <input
                    type="number"
                    value={intervalSeconds}
                    onChange={(e) => setIntervalSeconds(e.target.value)}
                    className="w-full px-3 py-2 bg-slate-950 border border-slate-700 rounded-xl text-xs text-white font-mono font-bold"
                  />
                </div>
              </div>
            </div>

            <div className="pt-4 flex justify-between">
              <button
                onClick={() => setStep(2)}
                className="px-4 py-2 bg-slate-800 hover:bg-slate-700 text-slate-300 rounded-xl text-xs font-semibold"
              >
                Back
              </button>
              <button
                onClick={() => setStep(4)}
                className="px-6 py-2 bg-blue-600 hover:bg-blue-500 text-white rounded-xl text-xs font-bold"
              >
                Continue to Admin Setup
              </button>
            </div>
          </div>
        )}

        {/* STEP 4: Admin Account */}
        {step === 4 && (
          <div className="space-y-4">
            <h3 className="text-sm font-bold text-white">Step 4: Create Superadmin Account</h3>
            <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
              <div>
                <label className="block text-xs font-semibold text-slate-300 mb-1">Admin Full Name</label>
                <input
                  type="text"
                  value={adminName}
                  onChange={(e) => setAdminName(e.target.value)}
                  className="w-full px-3 py-2 bg-slate-950 border border-slate-700 rounded-xl text-xs text-white"
                />
              </div>
              <div>
                <label className="block text-xs font-semibold text-slate-300 mb-1">Admin Email</label>
                <input
                  type="email"
                  value={adminEmail}
                  onChange={(e) => setAdminEmail(e.target.value)}
                  className="w-full px-3 py-2 bg-slate-950 border border-slate-700 rounded-xl text-xs text-white"
                />
              </div>
              <div>
                <label className="block text-xs font-semibold text-slate-300 mb-1">Admin Username</label>
                <input
                  type="text"
                  value={adminUsername}
                  onChange={(e) => setAdminUsername(e.target.value)}
                  className="w-full px-3 py-2 bg-slate-950 border border-slate-700 rounded-xl text-xs text-white font-mono"
                />
              </div>
              <div>
                <label className="block text-xs font-semibold text-slate-300 mb-1">Password</label>
                <input
                  type="password"
                  value={adminPassword}
                  onChange={(e) => setAdminPassword(e.target.value)}
                  className="w-full px-3 py-2 bg-slate-950 border border-slate-700 rounded-xl text-xs text-white"
                />
              </div>
            </div>

            <div className="pt-4 flex justify-between">
              <button
                onClick={() => setStep(3)}
                className="px-4 py-2 bg-slate-800 hover:bg-slate-700 text-slate-300 rounded-xl text-xs font-semibold"
              >
                Back
              </button>
              <button
                onClick={() => setStep(5)}
                className="px-6 py-2 bg-blue-600 hover:bg-blue-500 text-white rounded-xl text-xs font-bold"
              >
                Review &amp; Install
              </button>
            </div>
          </div>
        )}

        {/* STEP 5: Confirm Install */}
        {step === 5 && (
          <div className="space-y-4">
            <h3 className="text-sm font-bold text-white">Step 5: Final Review &amp; Execution</h3>
            <div className="p-4 rounded-xl bg-slate-950 border border-slate-800 text-xs space-y-2">
              <div>
                <span className="text-slate-400">Database:</span>{" "}
                <strong className="text-white">{dbName} on {dbHost}</strong>
              </div>
              <div>
                <span className="text-slate-400">Schedule:</span>{" "}
                <strong className="text-white">{startTime} AM • {totalSerials} Serials • {intervalSeconds}s Interval</strong>
              </div>
              <div>
                <span className="text-slate-400">Admin:</span>{" "}
                <strong className="text-white">{adminUsername} ({adminEmail})</strong>
              </div>
            </div>

            <div className="pt-4 flex justify-between">
              <button
                onClick={() => setStep(4)}
                className="px-4 py-2 bg-slate-800 hover:bg-slate-700 text-slate-300 rounded-xl text-xs font-semibold"
              >
                Back
              </button>
              <button
                disabled={loading}
                onClick={handleExecuteInstall}
                className="px-8 py-2.5 bg-gradient-to-r from-emerald-600 to-teal-600 hover:from-emerald-500 hover:to-teal-500 text-white rounded-xl text-xs font-extrabold shadow-lg shadow-emerald-600/30 flex items-center gap-2"
              >
                <CheckCircle2 className="w-4 h-4" />
                <span>{loading ? "Migrating Tables &amp; Provisioning..." : "Execute Installation Now"}</span>
              </button>
            </div>
          </div>
        )}

        {/* STEP 6: Complete */}
        {step === 6 && (
          <div className="text-center py-6 space-y-4">
            <div className="w-16 h-16 rounded-full bg-emerald-500/10 text-emerald-400 flex items-center justify-center mx-auto text-2xl font-bold">
              ✓
            </div>
            <h2 className="text-2xl font-extrabold text-white">Installation Completed Successfully!</h2>
            <p className="text-xs text-slate-300 max-w-md mx-auto leading-relaxed">
              MySQL schema applied, 5 daily serial schedule initialized (07:05 AM start, 1m interval), superadmin credentials saved, and installation lockfile generated.
            </p>
            <div className="pt-4">
              <a
                href="/"
                className="inline-block px-8 py-3 bg-blue-600 hover:bg-blue-500 text-white font-bold rounded-xl text-xs shadow-xl shadow-blue-600/30 transition-all hover:scale-105"
              >
                Go to Admin Dashboard →
              </a>
            </div>
          </div>
        )}
      </div>
    </div>
  );
};
