"use client";

import { useState, useEffect } from "react";
import { useRouter } from "next/navigation";
import { 
  User, MapPin, Fingerprint, BookOpenCheck, 
  ArrowLeft, Navigation, Smartphone, ChevronLeft 
} from "lucide-react";
import Link from "next/link";

export default function AdminCreateMilitantPage() {
  const router = useRouter();
  const [step, setStep] = useState(1);
  const [loading, setLoading] = useState(false);
  const [message, setMessage] = useState("");
  const [coloniasDisponibles, setColoniasDisponibles] = useState<any[]>([]);
  const [newMilitantId, setNewMilitantId] = useState<number | null>(null);

  const [form, setForm] = useState({
    first_name: "", last_name_paternal: "", last_name_maternal: "",
    birth_date: "", sex: "", curp: "", elector_key: "",
    section_number: "", street: "", ext_number: "", int_number: "",
    neighborhood: "", postal_code: "", reference_text: "",
    phone: "", notes: "", latitude: null as any, longitude: null as any,
  });

  const [userData, setUserData] = useState({ role: "militant", email: "", password: "" });

  const inputClass = "w-full rounded-2xl border border-gray-800 bg-[#0d0d0d] p-3 text-sm text-white focus:border-blue-500 outline-none transition-all";

  // --- GEOLOCALIZACIÓN ---
  useEffect(() => {
    if ("geolocation" in navigator) {
      navigator.geolocation.getCurrentPosition((pos) => {
        setForm(prev => ({ ...prev, latitude: pos.coords.latitude, longitude: pos.coords.longitude }));
      });
    }
  }, []);

  // --- ALGORITMO CURP ---
  const generarCurp = (f: any) => {
    try {
      if (!f.first_name || !f.last_name_paternal || !f.birth_date || !f.sex) return "";
      const nom = f.first_name.trim().toUpperCase();
      const pat = f.last_name_paternal.trim().toUpperCase();
      const mat = (f.last_name_maternal || "X").trim().toUpperCase();
      const [y, m, d] = f.birth_date.split("-");
      const iniciales = pat[0] + (pat.substring(1).match(/[AEIOU]/)?.[0] || "X") + mat[0] + nom[0];
      const sexo = f.sex === "M" ? "H" : "M";
      return (iniciales + y.substring(2) + m + d + sexo + "MSXXX").toUpperCase();
    } catch (e) { return ""; }
  };

  const handleInputChange = (e: any) => {
    const { name, value } = e.target;
    let nf = { ...form, [name]: value };
    if (name === "neighborhood") {
      const z = coloniasDisponibles.find(c => c.colonia === value);
      if (z) nf.section_number = z.section_number.toString();
    }
    if (["first_name", "last_name_paternal", "birth_date", "sex"].includes(name)) {
      nf.curp = generarCurp(nf);
    }
    setForm(nf);
  };

  useEffect(() => {
    if (form.postal_code.length === 5) {
      fetch(`/api/sections?cp=${form.postal_code}`).then(r => r.json()).then(d => setColoniasDisponibles(d));
    }
  }, [form.postal_code]);

  async function handleMilitantSubmit(e: any) {
    e.preventDefault();
    setLoading(true);
    try {
      const res = await fetch("/api/militants/create", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify(form),
      });
      const data = await res.json();
      if (!res.ok) {
        if (data.error?.includes("CURP")) throw new Error("⚠️ ERROR: CURP ya registrado.");
        throw new Error(data.error || "Error al procesar");
      }
      setNewMilitantId(data.id);
      localStorage.setItem("last_militant_id", data.id.toString());
      setStep(2);
      window.scrollTo({ top: 0, behavior: 'smooth' });
    } catch (err: any) { setMessage(err.message); } finally { setLoading(false); }
  }

  async function handleUserSubmit() {
    setLoading(true);
    const mid = newMilitantId || localStorage.getItem("last_militant_id");
    if (userData.role === "militant") {
      router.push(`/admin/militants/upload-ine?id=${mid}`);
      return;
    }
    try {
      const res = await fetch("/api/users/create", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ ...userData, full_name: `${form.first_name} ${form.last_name_paternal}`, phone: form.phone, militant_id: mid }),
      });
      if (res.ok) router.push(`/admin/militants/upload-ine?id=${mid}`);
    } catch (err: any) { setMessage("Error al crear acceso"); } finally { setLoading(false); }
  }

  // --- PASO 2: ASIGNACIÓN DE ROL (Aislado para evitar bloqueos) ---
  if (step === 2) {
    return (
      <div className="min-h-screen bg-black text-white p-6 flex flex-col items-center justify-center">
        <div className="w-full max-w-md space-y-8 animate-in fade-in zoom-in duration-300">
          <button onClick={() => setStep(1)} className="text-blue-500 flex items-center gap-2 font-black uppercase text-[10px]">
            <ChevronLeft size={16}/> Regresar a datos territoriales
          </button>
          
          <h1 className="text-4xl font-black uppercase italic text-blue-500 tracking-tighter">Nivel de Acceso</h1>

          <div className="grid grid-cols-1 gap-4">
            {["militant", "leader", "brigadist"].map((r) => (
              <button 
                key={r}
                type="button"
                onClick={() => setUserData({ ...userData, role: r })}
                className={`w-full p-6 rounded-3xl border-2 text-left transition-all ${userData.role === r ? 'border-blue-500 bg-blue-500/10 shadow-[0_0_20px_rgba(59,130,246,0.15)]' : 'border-gray-900 bg-[#0a0a0a]'}`}
              >
                <div className="flex justify-between items-center">
                  <span className={`text-xl font-black uppercase italic ${userData.role === r ? 'text-white' : 'text-gray-600'}`}>{r}</span>
                  <div className={`w-6 h-6 rounded-full border-2 flex items-center justify-center ${userData.role === r ? 'border-blue-500' : 'border-gray-800'}`}>
                    {userData.role === r && <div className="w-3 h-3 bg-blue-500 rounded-full" />}
                  </div>
                </div>
              </button>
            ))}
          </div>

          {userData.role !== "militant" && (
            <div className="space-y-4 p-6 bg-[#0a0a0a] rounded-3xl border border-gray-900 animate-in slide-in-from-top-4 duration-500">
              <p className="text-[9px] font-black text-blue-500 uppercase tracking-widest italic">Credenciales de Acceso</p>
              <input placeholder="Email" className={inputClass} onChange={e => setUserData({...userData, email: e.target.value})} />
              <input type="password" placeholder="Password" className={inputClass} onChange={e => setUserData({...userData, password: e.target.value})} />
            </div>
          )}

          <button 
            onClick={handleUserSubmit} 
            disabled={loading}
            className="w-full bg-blue-600 py-5 rounded-3xl font-black uppercase italic text-xl shadow-lg shadow-blue-600/20 active:scale-95 transition-all"
          >
            {loading ? "Sincronizando..." : "Finalizar y subir INE"}
          </button>
          {message && <p className="text-red-500 text-center font-black uppercase text-xs animate-pulse">{message}</p>}
        </div>
      </div>
    );
  }

  // --- PASO 1: DATOS TERRITORIALES (Con todos los campos) ---
  return (
    <div className="min-h-screen bg-[#050505] text-white p-4 font-sans pb-20">
      <div className="max-w-md mx-auto space-y-6">
        <header className="flex justify-between items-center">
          <Link href="/admin/dashboard" className="px-4 py-2 bg-[#0a0a0a] border border-gray-900 rounded-2xl text-blue-500 font-black uppercase text-[10px]">Dashboard</Link>
          <div className={`flex items-center gap-1 text-[8px] font-black uppercase ${form.latitude ? 'text-green-500 animate-pulse' : 'text-gray-700'}`}>
            <Navigation size={12}/> {form.latitude ? 'GPS ACTIVO' : 'Buscando Señal...'}
          </div>
        </header>

        <h1 className="text-3xl font-black italic uppercase tracking-tighter leading-none">Alta <span className="text-blue-500">Territorial</span></h1>

        <form onSubmit={handleMilitantSubmit} className="space-y-6">
          {/* SECCIÓN IDENTIDAD */}
          <div className="bg-[#0a0a0a] border border-gray-900 rounded-[2rem] p-6 space-y-4 shadow-2xl">
            <input name="first_name" placeholder="Nombre(s)" value={form.first_name} onChange={handleInputChange} className={inputClass} required />
            <div className="grid grid-cols-2 gap-3">
              <input name="last_name_paternal" placeholder="Ap. Paterno" value={form.last_name_paternal} onChange={handleInputChange} className={inputClass} required />
              <input name="last_name_maternal" placeholder="Ap. Materno" value={form.last_name_maternal} onChange={handleInputChange} className={inputClass} />
            </div>
            <div className="grid grid-cols-2 gap-3">
              <div className="space-y-1">
                <label className="text-[8px] text-gray-600 font-black uppercase ml-2 italic">Nacimiento</label>
                <input name="birth_date" type="date" value={form.birth_date} onChange={handleInputChange} className={inputClass} required />
              </div>
              <div className="space-y-1">
                <label className="text-[8px] text-gray-600 font-black uppercase ml-2 italic">Género</label>
                <select name="sex" value={form.sex} onChange={handleInputChange} className={inputClass} required>
                    <option value="">...</option>
                    <option value="M">HOMBRE</option>
                    <option value="F">MUJER</option>
                </select>
              </div>
            </div>
          </div>

          {/* SECCIÓN OFICIAL */}
          <div className="bg-[#0a0a0a] border border-gray-900 rounded-[2rem] p-6 space-y-4 shadow-2xl">
            <div className="space-y-1">
                <label className="text-[8px] text-blue-500 font-black uppercase ml-2">CURP Sugerido</label>
                <input name="curp" placeholder="CURP" value={form.curp} className={`${inputClass} text-blue-400 font-mono`} readOnly />
            </div>
            <input name="elector_key" placeholder="CLAVE DE ELECTOR" onChange={e => setForm({...form, elector_key: e.target.value.toUpperCase()})} className={inputClass} required />
            <input name="phone" placeholder="Número de Celular" value={form.phone} onChange={handleInputChange} className={inputClass} required />
          </div>

          {/* SECCIÓN DIRECCIÓN COMPLETA */}
          <div className="bg-[#0a0a0a] border border-gray-900 rounded-[2rem] p-6 space-y-4 shadow-2xl">
            <div className="grid grid-cols-2 gap-3">
              <input name="postal_code" placeholder="C.P." value={form.postal_code} onChange={handleInputChange} maxLength={5} className={inputClass} required />
              <input name="section_number" value={form.section_number} placeholder="Sección" className={`${inputClass} border-purple-900/40 text-purple-400 font-black`} readOnly />
            </div>
            <select name="neighborhood" value={form.neighborhood} onChange={handleInputChange} className={inputClass} required>
              <option value="">Seleccionar Colonia...</option>
              {coloniasDisponibles.map((c, i) => <option key={i} value={c.colonia}>{c.colonia}</option>)}
            </select>
            <input name="street" placeholder="Nombre de la Calle" value={form.street} onChange={handleInputChange} className={inputClass} required />
            <div className="grid grid-cols-2 gap-3">
              <input name="ext_number" placeholder="No. Exterior" value={form.ext_number} onChange={handleInputChange} className={inputClass} required />
              <input name="int_number" placeholder="No. Interior" value={form.int_number} onChange={handleInputChange} className={inputClass} />
            </div>
            {/* CAMPOS AGREGADOS DE VUELTA */}
            <textarea name="reference_text" placeholder="Referencias de la fachada o ubicación..." value={form.reference_text} onChange={handleInputChange} className={`${inputClass} h-16 resize-none`} />
            <textarea name="notes" placeholder="Notas u observaciones del registro..." value={form.notes} onChange={handleInputChange} className={`${inputClass} h-16 resize-none`} />
          </div>

          {message && <p className="text-red-500 text-center font-black uppercase text-[10px] italic">{message}</p>}
          
          <button type="submit" disabled={loading} className="w-full bg-blue-600 py-5 rounded-3xl font-black uppercase italic text-xl shadow-xl active:scale-95 transition-all">
            {loading ? "SINCRONIZANDO..." : "PASO SIGUIENTE"}
          </button>
        </form>
      </div>
    </div>
  );
}