"use client";

import { useState } from "react";
import { useRouter } from "next/navigation";
import { CheckCircle2, Lock, Mail, Server } from "lucide-react";

export default function SetupPage() {
  const router = useRouter();
  const [step, setStep] = useState(1);
  const [isInstalling, setIsInstalling] = useState(false);
  const [error, setError] = useState("");

  const [db, setDb] = useState({
    host: "localhost",
    port: "5432",
    user: "postgres",
    pass: "",
    name: "rima_academy",
  });

  const [smtp, setSmtp] = useState({
    host: "",
    port: "465",
    user: "",
    pass: "",
  });

  const [admin, setAdmin] = useState({
    email: "",
    password: "",
  });

  // Password strength meter logic
  const calculateStrength = (pass: string) => {
    let score = 0;
    if (pass.length > 6) score += 1;
    if (pass.length > 10) score += 1;
    if (/[A-Z]/.test(pass)) score += 1;
    if (/[0-9]/.test(pass)) score += 1;
    if (/[^A-Za-z0-9]/.test(pass)) score += 1;
    return score; // 0 to 5
  };
  const strength = calculateStrength(admin.password);
  const strengthColors = ["bg-slate-700", "bg-rose-500", "bg-orange-500", "bg-yellow-500", "bg-emerald-500", "bg-emerald-400"];
  const strengthLabels = ["Foarte Slabă", "Slabă", "Decentă", "Bună", "Puternică", "Foarte Puternică"];

  const installSystem = async () => {
    if (!admin.email || !admin.password) {
      setError("Te rugăm să completezi datele pentru contul de Admin.");
      return;
    }
    
    setIsInstalling(true);
    setError("");

    try {
      const res = await fetch("/api/setup", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ db, smtp, admin }),
      });

      const data = await res.json();

      if (!data.success) {
        setError(data.error || "A aparut o eroare necunoscuta.");
        setIsInstalling(false);
        return;
      }

      setStep(3); // Go to done
    } catch (err) {
      setError("Conexiunea la server a eșuat.");
    } finally {
      setIsInstalling(false);
    }
  };

  return (
    <div className="min-h-screen flex items-center justify-center bg-slate-950 relative overflow-hidden py-12">
      <div className="absolute -top-[40%] -left-[20%] h-[80%] w-[60%] rounded-full bg-indigo-900/20 blur-[120px]"></div>
      <div className="absolute -bottom-[40%] -right-[20%] h-[80%] w-[60%] rounded-full bg-blue-900/20 blur-[120px]"></div>

      <div className="relative w-full max-w-3xl p-6 z-10">
        <div className="mb-8 text-center">
          <h1 className="text-4xl font-extrabold tracking-tight text-white mb-2">RIMA Platform Setup</h1>
          <p className="text-slate-400">Configurează conexiunea cu baza de date, serverul de email (SMTP) și contul de administrator.</p>
        </div>

        <div className="bg-slate-900/80 border border-slate-800 rounded-2xl shadow-2xl backdrop-blur-xl overflow-hidden">
          
          <div className="flex border-b border-slate-800/50 bg-slate-950/50">
            <div className={`flex-1 py-4 px-6 text-center border-r border-slate-800/50 ${step >= 1 ? "text-indigo-400" : "text-slate-500"}`}>
              <div className="text-xs font-bold uppercase tracking-wider mb-1">Pasul 1</div>
              <div className="text-sm font-medium">Configurare Sistem</div>
            </div>
            <div className={`flex-1 py-4 px-6 text-center ${step >= 3 ? "text-indigo-400" : "text-slate-500"}`}>
              <div className="text-xs font-bold uppercase tracking-wider mb-1">Pasul 2</div>
              <div className="text-sm font-medium">Finalizare</div>
            </div>
          </div>

          {step === 1 && (
            <div className="p-8 space-y-8">
              {error && (
                <div className="bg-rose-500/10 border border-rose-500/20 text-rose-400 p-4 rounded-xl text-sm font-medium">
                  {error}
                </div>
              )}
              
              {/* Database Section */}
              <div>
                <h3 className="text-lg font-semibold text-white mb-4 flex items-center gap-2"><Server className="w-5 h-5 text-indigo-400"/> 1. PostgreSQL Database</h3>
                <div className="grid grid-cols-2 gap-4">
                  <div>
                    <label className="block text-xs font-semibold uppercase tracking-wider text-slate-400 mb-2">DB Host</label>
                    <input type="text" value={db.host} onChange={(e) => setDb({...db, host: e.target.value})} className="w-full rounded-xl border border-slate-700 bg-slate-800/50 px-4 py-3 text-sm text-white focus:border-indigo-500 focus:outline-none" />
                  </div>
                  <div>
                    <label className="block text-xs font-semibold uppercase tracking-wider text-slate-400 mb-2">DB Port</label>
                    <input type="text" value={db.port} onChange={(e) => setDb({...db, port: e.target.value})} className="w-full rounded-xl border border-slate-700 bg-slate-800/50 px-4 py-3 text-sm text-white focus:border-indigo-500 focus:outline-none" />
                  </div>
                  <div>
                    <label className="block text-xs font-semibold uppercase tracking-wider text-slate-400 mb-2">DB Username</label>
                    <input type="text" value={db.user} onChange={(e) => setDb({...db, user: e.target.value})} className="w-full rounded-xl border border-slate-700 bg-slate-800/50 px-4 py-3 text-sm text-white focus:border-indigo-500 focus:outline-none" />
                  </div>
                  <div>
                    <label className="block text-xs font-semibold uppercase tracking-wider text-slate-400 mb-2">DB Password</label>
                    <input type="password" value={db.pass} onChange={(e) => setDb({...db, pass: e.target.value})} className="w-full rounded-xl border border-slate-700 bg-slate-800/50 px-4 py-3 text-sm text-white focus:border-indigo-500 focus:outline-none" />
                  </div>
                  <div className="col-span-2">
                    <label className="block text-xs font-semibold uppercase tracking-wider text-slate-400 mb-2">Database Name</label>
                    <input type="text" value={db.name} onChange={(e) => setDb({...db, name: e.target.value})} className="w-full rounded-xl border border-slate-700 bg-slate-800/50 px-4 py-3 text-sm text-white focus:border-indigo-500 focus:outline-none" />
                  </div>
                </div>
              </div>

              {/* SMTP Section */}
              <div className="border-t border-slate-800 pt-8">
                <h3 className="text-lg font-semibold text-white mb-4 flex items-center gap-2"><Mail className="w-5 h-5 text-indigo-400"/> 2. Server Email (SMTP - pt. Forgot Password)</h3>
                <div className="grid grid-cols-2 gap-4">
                  <div>
                    <label className="block text-xs font-semibold uppercase tracking-wider text-slate-400 mb-2">SMTP Host</label>
                    <input type="text" value={smtp.host} onChange={(e) => setSmtp({...smtp, host: e.target.value})} placeholder="mail.rima-academy.com" className="w-full rounded-xl border border-slate-700 bg-slate-800/50 px-4 py-3 text-sm text-white focus:border-indigo-500 focus:outline-none" />
                  </div>
                  <div>
                    <label className="block text-xs font-semibold uppercase tracking-wider text-slate-400 mb-2">SMTP Port</label>
                    <input type="text" value={smtp.port} onChange={(e) => setSmtp({...smtp, port: e.target.value})} placeholder="465" className="w-full rounded-xl border border-slate-700 bg-slate-800/50 px-4 py-3 text-sm text-white focus:border-indigo-500 focus:outline-none" />
                  </div>
                  <div>
                    <label className="block text-xs font-semibold uppercase tracking-wider text-slate-400 mb-2">Email Username</label>
                    <input type="text" value={smtp.user} onChange={(e) => setSmtp({...smtp, user: e.target.value})} placeholder="no-reply@rima-academy.com" className="w-full rounded-xl border border-slate-700 bg-slate-800/50 px-4 py-3 text-sm text-white focus:border-indigo-500 focus:outline-none" />
                  </div>
                  <div>
                    <label className="block text-xs font-semibold uppercase tracking-wider text-slate-400 mb-2">Email Password</label>
                    <input type="password" value={smtp.pass} onChange={(e) => setSmtp({...smtp, pass: e.target.value})} className="w-full rounded-xl border border-slate-700 bg-slate-800/50 px-4 py-3 text-sm text-white focus:border-indigo-500 focus:outline-none" />
                  </div>
                </div>
              </div>

              {/* Admin Section */}
              <div className="border-t border-slate-800 pt-8">
                <h3 className="text-lg font-semibold text-white mb-4 flex items-center gap-2"><Lock className="w-5 h-5 text-indigo-400"/> 3. Primul Cont de Administrator</h3>
                <div className="grid grid-cols-2 gap-4">
                  <div className="col-span-2 md:col-span-1">
                    <label className="block text-xs font-semibold uppercase tracking-wider text-slate-400 mb-2">Admin Email</label>
                    <input type="email" value={admin.email} onChange={(e) => setAdmin({...admin, email: e.target.value})} placeholder="admin@rima-academy.com" className="w-full rounded-xl border border-slate-700 bg-slate-800/50 px-4 py-3 text-sm text-white focus:border-indigo-500 focus:outline-none" required />
                  </div>
                  <div className="col-span-2 md:col-span-1">
                    <label className="block text-xs font-semibold uppercase tracking-wider text-slate-400 mb-2 flex justify-between">
                      <span>Admin Password</span>
                      <span className="text-[10px] text-slate-500">{strengthLabels[strength]}</span>
                    </label>
                    <input type="password" value={admin.password} onChange={(e) => setAdmin({...admin, password: e.target.value})} className="w-full rounded-xl border border-slate-700 bg-slate-800/50 px-4 py-3 text-sm text-white focus:border-indigo-500 focus:outline-none" required />
                    <div className="mt-2 flex gap-1 h-1.5">
                      {[...Array(5)].map((_, i) => (
                        <div key={i} className={`flex-1 rounded-full ${i < strength ? strengthColors[strength] : 'bg-slate-700'}`}></div>
                      ))}
                    </div>
                  </div>
                </div>
              </div>

              <div className="pt-4">
                <button onClick={installSystem} disabled={isInstalling} className="w-full bg-indigo-600 hover:bg-indigo-500 text-white py-4 rounded-xl font-bold transition-all shadow-lg shadow-indigo-500/20 flex justify-center items-center gap-2">
                  {isInstalling ? (
                    <>
                      <svg className="animate-spin h-5 w-5 text-white" xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24">
                        <circle className="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" strokeWidth="4"></circle>
                        <path className="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"></path>
                      </svg>
                      Instalare & Configurare Platformă...
                    </>
                  ) : (
                    "Instalează Platforma"
                  )}
                </button>
              </div>
            </div>
          )}

          {step === 3 && (
            <div className="p-12 text-center space-y-6">
              <div className="w-24 h-24 bg-emerald-500/20 text-emerald-400 rounded-full flex items-center justify-center mx-auto mb-6">
                <CheckCircle2 className="w-12 h-12" />
              </div>
              <h2 className="text-3xl font-bold text-white">Instalare Completă!</h2>
              <p className="text-slate-400 max-w-md mx-auto">
                Baza de date a fost conectată, SMTP-ul salvat, iar contul tău de administrator a fost creat cu succes.
              </p>
              
              <div className="pt-6">
                <button onClick={() => router.push("/login")} className="inline-block bg-white text-slate-900 px-10 py-4 rounded-xl font-bold hover:bg-slate-200 transition-colors shadow-lg">
                  Intră în Cont (Login)
                </button>
              </div>
            </div>
          )}

        </div>
      </div>
    </div>
  );
}
