"use client";

import { useState } from "react";
import { UploadCloud, CheckCircle2, AlertCircle, Loader2 } from "lucide-react";

export default function MigrationPage() {
  const [step, setStep] = useState(1);
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState("");
  const [success, setSuccess] = useState("");

  const [wpPath, setWpPath] = useState("/home/rimaacad/public_html/wp-config.php");
  const [detecting, setDetecting] = useState(false);

  const [dbCreds, setDbCreds] = useState({
    host: "localhost",
    user: "",
    password: "",
    database: "",
    prefix: "wp_",
  });

  const [migrationLogs, setMigrationLogs] = useState<string[]>([]);

  const handleAutoDetect = async () => {
    setDetecting(true);
    setError("");
    try {
      const res = await fetch("/api/migration/detect-wp", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ wpPath }),
      });
      const data = await res.json();
      if (!res.ok) throw new Error(data.error || "Nu am putut detecta wp-config.php");
      
      setDbCreds(data.credentials);
      setSuccess("Datele bazei de date au fost importate cu succes din wp-config.php!");
      setTimeout(() => setSuccess(""), 3000);
    } catch (err: any) {
      setError(err.message);
    } finally {
      setDetecting(false);
    }
  };

  const handleConnect = async () => {
    setLoading(true);
    setError("");
    try {
      const res = await fetch("/api/migration/connect", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify(dbCreds),
      });
      const data = await res.json();
      if (!res.ok) throw new Error(data.error || "Eroare la conectare");
      
      setSuccess("Conectare reușită la baza de date veche!");
      setMigrationLogs((prev) => [...prev, `[SUCCESS] Baza de date WordPress găsită. Cursuri: ${data.counts.courses}, Utilizatori: ${data.counts.users}`]);
      setTimeout(() => {
        setSuccess("");
        setStep(2);
      }, 2000);
    } catch (err: any) {
      setError(err.message);
    } finally {
      setLoading(false);
    }
  };

  const handleMigrateCourses = async () => {
    setLoading(true);
    setError("");
    try {
      const res = await fetch("/api/migration/courses", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify(dbCreds),
      });
      const data = await res.json();
      
      // Show server logs regardless of success/failure
      if (data.logs && Array.isArray(data.logs)) {
        setMigrationLogs((prev) => [...prev, ...data.logs]);
      }
      
      if (!res.ok) throw new Error(data.error || "Eroare migrare cursuri");
      
      setMigrationLogs((prev) => [
        ...prev,
        `[SUCCESS] ${data.migrated} cursuri migrate cu succes. (${data.skipped || 0} sarite)`
      ]);
      setTimeout(() => setStep(3), 1500);
    } catch (err: any) {
      setError(err.message);
    } finally {
      setLoading(false);
    }
  };

  const handleMigrateUsers = async () => {
    setLoading(true);
    setError("");
    try {
      const res = await fetch("/api/migration/users", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify(dbCreds),
      });
      const data = await res.json();
      if (!res.ok) throw new Error(data.error || "Eroare migrare utilizatori");
      
      setMigrationLogs((prev) => [...prev, `[SUCCESS] ${data.migrated} utilizatori (și date B2B) au fost migrați.`]);
      setStep(4);
    } catch (err: any) {
      setError(err.message);
    } finally {
      setLoading(false);
    }
  };

  return (
    <div className="min-h-screen bg-[#0F111A] p-8 text-slate-300 font-sans">
      <div className="max-w-4xl mx-auto mt-10">
        <div className="flex items-center gap-3 mb-4">
          <UploadCloud className="w-8 h-8 text-indigo-400" />
          <h1 className="text-3xl font-bold text-white tracking-tight">Data Migration Assistant</h1>
        </div>
        <p className="text-slate-400 mb-10">
          Acest asistent te ajută să transferi cursurile, lecțiile, studenții și datele B2B din baza de date WordPress/WooCommerce veche în noua structură a platformei RIMA Academy (NextJS/PostgreSQL).
        </p>

        {/* Stepper */}
        <div className="grid grid-cols-4 border border-white/10 rounded-t-xl bg-[#1A1D27] overflow-hidden">
          {[
            { id: 1, label: "Analiză Date Vechi" },
            { id: 2, label: "Migrare Cursuri & Lecții" },
            { id: 3, label: "Migrare Utilizatori & Facturi" },
            { id: 4, label: "Finalizare & Verificare" },
          ].map((s) => (
            <div
              key={s.id}
              className={`py-4 px-2 text-center border-r border-white/5 last:border-0 text-sm font-semibold transition-colors ${
                step === s.id
                  ? "bg-indigo-600/10 text-indigo-400 border-b-2 border-b-indigo-500"
                  : step > s.id
                  ? "text-emerald-400"
                  : "text-slate-500"
              }`}
            >
              <div className="text-xs mb-1 opacity-60">PASUL {s.id}</div>
              {s.label}
            </div>
          ))}
        </div>

        {/* Content */}
        <div className="bg-[#1A1D27] border border-t-0 border-white/10 rounded-b-xl p-8 min-h-[300px] flex flex-col justify-between shadow-2xl relative">
          
          {error && (
            <div className="mb-6 p-4 bg-rose-500/10 border border-rose-500/20 rounded-xl flex gap-3 text-rose-400 text-sm">
              <AlertCircle className="w-5 h-5 shrink-0" />
              <p>{error}</p>
            </div>
          )}
          {success && (
            <div className="mb-6 p-4 bg-emerald-500/10 border border-emerald-500/20 rounded-xl flex gap-3 text-emerald-400 text-sm">
              <CheckCircle2 className="w-5 h-5 shrink-0" />
              <p>{success}</p>
            </div>
          )}

          {step === 1 && (
            <div className="space-y-6 max-w-xl">
              <div>
                <h2 className="text-xl font-bold text-white mb-2">Auto-Detectare</h2>
                <p className="text-sm text-slate-400 mb-4">Dacă site-ul vechi e pe același server, introdu calea către wp-config.php pentru a extrage automat datele.</p>
                <div className="flex gap-2">
                  <input type="text" value={wpPath} onChange={e => setWpPath(e.target.value)} className="flex-1 bg-[#0F111A] border border-white/10 rounded-lg px-4 py-2 text-sm text-white focus:border-indigo-500 outline-none" />
                  <button 
                    onClick={handleAutoDetect} 
                    disabled={detecting}
                    className="px-4 py-2 bg-slate-800 hover:bg-slate-700 text-white rounded-lg text-sm font-semibold transition-colors disabled:opacity-50 flex items-center gap-2"
                  >
                    {detecting && <Loader2 className="w-4 h-4 animate-spin" />}
                    Detectează
                  </button>
                </div>
              </div>

              <div className="h-px bg-white/10 w-full my-4"></div>

              <h2 className="text-xl font-bold text-white mb-4">Sau introdu datele manual</h2>
              <div className="grid grid-cols-2 gap-4">
                <div>
                  <label className="block text-xs uppercase tracking-wider text-slate-500 mb-1">Host MySQL</label>
                  <input type="text" value={dbCreds.host} onChange={e => setDbCreds({...dbCreds, host: e.target.value})} className="w-full bg-[#0F111A] border border-white/10 rounded-lg px-4 py-2 text-white focus:border-indigo-500 outline-none" />
                </div>
                <div>
                  <label className="block text-xs uppercase tracking-wider text-slate-500 mb-1">Prefix Tabele</label>
                  <input type="text" value={dbCreds.prefix} onChange={e => setDbCreds({...dbCreds, prefix: e.target.value})} className="w-full bg-[#0F111A] border border-white/10 rounded-lg px-4 py-2 text-white focus:border-indigo-500 outline-none" />
                </div>
                <div>
                  <label className="block text-xs uppercase tracking-wider text-slate-500 mb-1">Utilizator MySQL</label>
                  <input type="text" value={dbCreds.user} onChange={e => setDbCreds({...dbCreds, user: e.target.value})} className="w-full bg-[#0F111A] border border-white/10 rounded-lg px-4 py-2 text-white focus:border-indigo-500 outline-none" />
                </div>
                <div>
                  <label className="block text-xs uppercase tracking-wider text-slate-500 mb-1">Parolă MySQL</label>
                  <input type="password" value={dbCreds.password} onChange={e => setDbCreds({...dbCreds, password: e.target.value})} className="w-full bg-[#0F111A] border border-white/10 rounded-lg px-4 py-2 text-white focus:border-indigo-500 outline-none" />
                </div>
                <div className="col-span-2">
                  <label className="block text-xs uppercase tracking-wider text-slate-500 mb-1">Nume Bază de Date (WordPress)</label>
                  <input type="text" value={dbCreds.database} onChange={e => setDbCreds({...dbCreds, database: e.target.value})} className="w-full bg-[#0F111A] border border-white/10 rounded-lg px-4 py-2 text-white focus:border-indigo-500 outline-none" />
                </div>
              </div>
            </div>
          )}

          {step === 2 && (
            <div>
              <h2 className="text-xl font-bold text-white mb-4">Migrare Cursuri WordPress</h2>
              <p className="text-slate-400 mb-4">Apasă <strong className="text-white">"Continuă"</strong> pentru a migra toate cursurile detectate în noua bază de date RIMA.</p>
              <p className="text-xs text-slate-500 mb-6">Se vor detecta automat: WooCommerce Products, LearnDash, LifterLMS, Tutor LMS și orice alt tip de curs WordPress.</p>
              
              {migrationLogs.length > 0 && (
                <div className="bg-[#0F111A] rounded-xl border border-white/5 p-4 max-h-64 overflow-y-auto">
                  {migrationLogs.map((log, i) => (
                    <div
                      key={i}
                      className={`text-xs font-mono mb-1 ${
                        log.startsWith('[OK') ? 'text-emerald-400' :
                        log.startsWith('[SKIP') ? 'text-amber-400' :
                        log.startsWith('[INFO') ? 'text-slate-400' :
                        log.startsWith('[SUCCESS') ? 'text-emerald-300 font-bold' :
                        'text-rose-400'
                      }`}
                    >
                      {log}
                    </div>
                  ))}
                </div>
              )}
            </div>
          )}

          {step === 3 && (
            <div>
              <h2 className="text-xl font-bold text-white mb-4">Migrare Utilizatori & Date WooCommerce</h2>
              <p className="text-slate-400 mb-6">Acum vom importa conturile studenților, istoricul lor, și facturile asociate profilurilor B2B/B2C din WooCommerce.</p>
              
              {migrationLogs.map((log, i) => (
                <div key={i} className="text-sm font-mono text-emerald-400 mb-2">{log}</div>
              ))}
            </div>
          )}

          {step === 4 && (
            <div className="text-center py-10">
              <CheckCircle2 className="w-16 h-16 text-emerald-500 mx-auto mb-4" />
              <h2 className="text-2xl font-bold text-white mb-2">Migrare Finalizată cu Succes!</h2>
              <p className="text-slate-400">Sistemul vechi a fost dezactivat, iar baza nouă este populată.</p>
              <div className="mt-6 text-left bg-[#0F111A] p-4 rounded-xl border border-white/5 font-mono text-sm">
                {migrationLogs.map((log, i) => (
                  <div key={i} className="text-slate-300 mb-1">{log}</div>
                ))}
              </div>
            </div>
          )}

          {/* Footer Actions */}
          <div className="flex justify-between items-center mt-10 pt-6 border-t border-white/5">
            <button
              onClick={() => setStep(s => Math.max(1, s - 1))}
              disabled={step === 1 || step === 4 || loading}
              className="px-6 py-2 rounded-lg text-slate-400 hover:text-white transition-colors disabled:opacity-30"
            >
              Înapoi
            </button>
            
            {step === 1 && (
              <button
                onClick={handleConnect}
                disabled={loading || !dbCreds.database}
                className="px-6 py-2 bg-indigo-600 hover:bg-indigo-500 text-white rounded-lg font-semibold flex items-center gap-2 disabled:opacity-50 transition-all shadow-lg shadow-indigo-500/20"
              >
                {loading && <Loader2 className="w-4 h-4 animate-spin" />}
                Conectează-te
              </button>
            )}
            {step === 2 && (
              <button
                onClick={handleMigrateCourses}
                disabled={loading}
                className="px-6 py-2 bg-indigo-600 hover:bg-indigo-500 text-white rounded-lg font-semibold flex items-center gap-2 disabled:opacity-50 transition-all shadow-lg shadow-indigo-500/20"
              >
                {loading && <Loader2 className="w-4 h-4 animate-spin" />}
                Continuă
              </button>
            )}
            {step === 3 && (
              <button
                onClick={handleMigrateUsers}
                disabled={loading}
                className="px-6 py-2 bg-indigo-600 hover:bg-indigo-500 text-white rounded-lg font-semibold flex items-center gap-2 disabled:opacity-50 transition-all shadow-lg shadow-indigo-500/20"
              >
                {loading && <Loader2 className="w-4 h-4 animate-spin" />}
                Continuă
              </button>
            )}
            {step === 4 && (
              <a
                href="/admin"
                className="px-6 py-2 bg-emerald-600 hover:bg-emerald-500 text-white rounded-lg font-semibold transition-all shadow-lg shadow-emerald-500/20"
              >
                Mergi la Dashboard
              </a>
            )}
          </div>
        </div>
      </div>
    </div>
  );
}
