"use client";

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

interface Section {
  colonia: string;
  section_number: string | number;
}

export default function LeaderCreateMilitantPage() {
  const router = useRouter();
  const [step, setStep] = useState(1);
  const [loading, setLoading] = useState(false);
  const [message, setMessage] = useState("");
  const [coloniasDisponibles, setColoniasDisponibles] = useState<Section[]>([]);
  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: "",
  });

  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 placeholder-gray-600 focus:border-blue-500 outline-none transition-all box-border";

  // --- ALGORITMO CURP ---
  const filtrarInconvenientes = (str: string) => {
    const inconvenientes = ["BACA", "BAKA", "BUEI", "BUEY", "CACA", "CAKA", "CACO", "CAGA", "CAGO", "COCA", "COGE", "COGI", "COJA", "COJE", "COJI", "COJO", "COLA", "CULO", "FALO", "FETO", "GETA", "GUEI", "GUEY", "JETA", "JOTO", "KACA", "KAKA", "KAGO", "KOJO", "KULO", "MAME", "MAMO", "MEAR", "MEAS", "MEON", "MION", "MOCO", "MOKO", "MULA", "PEDA", "PEDO", "PENE", "PUTA", "PUTO", "QULO", "RATA", "ROBA", "ROBE", "ROBO", "RUIN", "SENO", "TETA", "VUEI", "VUEY", "WUEI", "WUEY"];
    return inconvenientes.includes(str) ? str.substring(0, 3) + "X" : str;
  };

  const primeraConsonanteInterna = (str: string) => {
    const s = str.substring(1).toUpperCase();
    const c = s.match(/[BCDFGHJKLMNPQRSTVWXYZ]/);
    return c ? c[0] : "X";
  };

  const generarCurpManual = (f: typeof form) => {
    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("-");
      let iniciales = pat.substring(0, 1);
      const vocalPat = pat.substring(1).match(/[AEIOU]/);
      iniciales += vocalPat ? vocalPat[0] : "X";
      iniciales += mat.substring(0, 1);
      iniciales += nom.substring(0, 1);
      const inicialesFiltradas = filtrarInconvenientes(iniciales);
      const fecha = y.substring(2) + m + d;
      // Ajuste de Sexo para CURP (H/M) pero en Formulario usaremos (M/F) para tu base de datos
      const sexoCurp = f.sex === "M" ? "H" : "M"; 
      const consonantes = primeraConsonanteInterna(pat) + primeraConsonanteInterna(mat) + primeraConsonanteInterna(nom);
      return (inicialesFiltradas + fecha + sexoCurp + "MS" + consonantes).toUpperCase();
    } catch (e) { return ""; }
  };

  const handleInputChange = (e: React.ChangeEvent<HTMLInputElement | HTMLSelectElement | HTMLTextAreaElement>) => {
    const { name, value } = e.target;
    let updatedForm = { ...form, [name]: value };
    if (name === "neighborhood") {
      const zona = coloniasDisponibles.find(c => c.colonia === value);
      if (zona) updatedForm.section_number = zona.section_number.toString();
    }
    if (["first_name", "last_name_paternal", "last_name_maternal", "birth_date", "sex"].includes(name)) {
      const curpPropuesta = generarCurpManual(updatedForm);
      if (curpPropuesta) updatedForm.curp = curpPropuesta;
    }
    setForm(updatedForm);
  };

  useEffect(() => {
    const loadColonias = async () => {
      if (form.postal_code.length === 5) {
        try {
          const res = await fetch(`/api/sections?cp=${form.postal_code}`);
          const data = await res.json();
          setColoniasDisponibles(Array.isArray(data) ? data : []);
        } catch (err) { console.error(err); }
      }
    };
    loadColonias();
  }, [form.postal_code]);

  async function handleMilitantSubmit(e: React.FormEvent) {
    e.preventDefault();
    setLoading(true);
    setMessage(""); 
    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) throw new Error(data.error || "Error al procesar");
      if (data.id) {
        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 (!mid) { setMessage("❌ ID no encontrado"); setLoading(false); return; }

    if (userData.role === "militant") {
      router.push(`/leader/militants/upload-ine?id=${mid}`);
      return;
    }

    try {
      const res = await fetch("/api/users/create", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({
          full_name: `${form.first_name} ${form.last_name_paternal} ${form.last_name_maternal}`.trim(),
          email: userData.email,
          password: userData.password,
          role: userData.role === "brigadist" ? "brigadist" : "militant",
          phone: form.phone,
          militant_id: mid
        }),
      });
      if (res.ok) {
        router.push(`/leader/militants/upload-ine?id=${mid}`);
      } else {
        const d = await res.json();
        throw new Error(d.error || "Error al crear usuario");
      }
    } catch (err: any) { setMessage(`❌ ${err.message}`); } finally { setLoading(false); }
  }

  return (
    <div className="min-h-screen bg-[#050505] text-white p-4 font-sans overflow-x-hidden">
      <div className="max-w-md mx-auto">
        <header className="mb-6">
          <Link href="/leader/dashboard" className="flex items-center gap-2 w-fit px-4 py-2 bg-[#0a0a0a] border border-gray-900 rounded-2xl text-blue-500">
            <ArrowLeft size={18} /> <span className="text-[10px] font-black uppercase tracking-widest text-gray-500">Volver</span>
          </Link>
        </header>

        {step === 1 ? (
          <form onSubmit={handleMilitantSubmit} className="space-y-6 pb-12">
            <div className="bg-[#0a0a0a] border border-gray-900 rounded-[2rem] p-6 shadow-2xl">
              <div className="flex items-center gap-3 mb-6 text-blue-500"><User size={22} /><h2 className="text-lg font-black uppercase italic text-white tracking-tighter">Identidad</h2></div>
              <div className="space-y-4">
                <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="Apellido Paterno" value={form.last_name_paternal} onChange={handleInputChange} className={inputClass} required />
                    <input name="last_name_maternal" placeholder="Apellido Materno" value={form.last_name_maternal} onChange={handleInputChange} className={inputClass} />
                </div>
                <div className="grid grid-cols-1 gap-4">
                    <div className="flex flex-col gap-1.5 w-full">
                      <label className="text-[9px] font-bold text-gray-600 uppercase ml-2 flex items-center gap-1"><CalendarDays size={10}/> Nacimiento</label>
                      <input name="birth_date" type="date" value={form.birth_date} onChange={handleInputChange} className={inputClass} required />
                    </div>
                    <div className="flex flex-col gap-1.5 w-full">
                      <label className="text-[9px] font-bold text-gray-600 uppercase ml-2 flex items-center gap-1"><Users size={10}/> Género</label>
                      <select name="sex" value={form.sex} onChange={handleInputChange} className={inputClass} required>
                        <option value="">Seleccionar...</option>
                        <option value="M">HOMBRE</option> 
                        <option value="F">MUJER</option>
                      </select>
                    </div>
                </div>
              </div>
            </div>

            <div className="bg-[#0a0a0a] border border-gray-900 rounded-[2rem] p-6 shadow-2xl">
              <div className="flex items-center gap-3 mb-6 text-blue-500"><BookOpenCheck size={22} /><h2 className="text-lg font-black uppercase italic text-white tracking-tighter">Validación</h2></div>
              <div className="space-y-4">
                <div className="space-y-1">
                  <label className="text-[9px] font-black text-blue-500 uppercase ml-2">CURP Sugerida</label>
                  <input name="curp" placeholder="CURP" value={form.curp} onChange={(e) => setForm({...form, curp: e.target.value.toUpperCase()})} className={`${inputClass} border-blue-900/40 text-blue-400 font-mono`} required />
                </div>
                <input name="elector_key" placeholder="CLAVE DE ELECTOR" value={form.elector_key} onChange={(e) => setForm({...form, elector_key: e.target.value.toUpperCase()})} className={`${inputClass} uppercase`} required />
                <input name="phone" placeholder="Teléfono" value={form.phone} onChange={handleInputChange} className={inputClass} />
              </div>
            </div>

            <div className="bg-[#0a0a0a] border border-gray-900 rounded-[2rem] p-6 shadow-2xl">
              <div className="flex items-center gap-3 mb-6 text-purple-500"><MapPin size={22} /><h2 className="text-lg font-black uppercase italic text-white tracking-tighter">Territorio</h2></div>
              <div className="space-y-4">
                <div className="grid grid-cols-2 gap-3">
                  <input name="postal_code" placeholder="C.P." value={form.postal_code} onChange={(e) => setForm({...form, postal_code: e.target.value.replace(/\D/g,'')})} maxLength={5} className={inputClass} required />
                  <input name="section_number" placeholder="Sección" value={form.section_number} onChange={handleInputChange} className={`${inputClass} border-purple-900/30 text-purple-300 font-black`} required />
                </div>
                <select name="neighborhood" value={form.neighborhood} onChange={handleInputChange} className={inputClass} disabled={coloniasDisponibles.length === 0} required>
                  <option value="">Colonia...</option>
                  {coloniasDisponibles.map((c, i) => <option key={i} value={c.colonia}>{c.colonia}</option>)}
                </select>
                <input name="street" placeholder="Calle" value={form.street} onChange={handleInputChange} className={inputClass} required />
                <div className="grid grid-cols-2 gap-3">
                  <input name="ext_number" placeholder="No. Ext" value={form.ext_number} onChange={handleInputChange} className={inputClass} required />
                  <input name="int_number" placeholder="No. Int" value={form.int_number} onChange={handleInputChange} className={inputClass} />
                </div>
                <input name="reference_text" placeholder="Referencias" value={form.reference_text} onChange={handleInputChange} className={inputClass} />
                <textarea name="notes" placeholder="Notas..." value={form.notes} onChange={handleInputChange} className={`${inputClass} h-20 resize-none`} />
              </div>
            </div>

            <button type="submit" disabled={loading} className="w-full rounded-xl bg-blue-600 py-4 font-black uppercase text-[11px] shadow-xl">
              {loading ? "PROCESANDO..." : "PASO SIGUIENTE"}
            </button>
          </form>
        ) : (
          <div className="bg-[#0a0a0a] border border-gray-900 rounded-[2.5rem] p-8 shadow-2xl space-y-6">
              <h1 className="text-xl font-black uppercase italic text-blue-500 text-center">Nivel de Integrante</h1>
              <div className="space-y-3">
                 {/* BOTONES DE ACCIÓN DIRECTA PARA EVITAR ERRORES DE SELECCIÓN */}
                 <button 
                  type="button" 
                  onClick={() => setUserData({...userData, role: "militant"})}
                  className={`w-full flex items-center justify-between p-5 border rounded-2xl transition-all ${userData.role === "militant" ? 'border-blue-500 bg-blue-900/10 ring-1 ring-blue-500' : 'border-gray-800 bg-[#0d0d0d]'}`}
                 >
                    <div className="flex flex-col items-start">
                      <span className={`font-black uppercase text-[11px] ${userData.role === "militant" ? 'text-blue-400' : 'text-gray-400'}`}>Militante</span>
                      <span className="text-[8px] text-gray-600 font-bold uppercase">Solo registro territorial</span>
                    </div>
                    {userData.role === "militant" && <div className="w-2.5 h-2.5 bg-blue-500 rounded-full" />}
                 </button>

                 <button 
                  type="button" 
                  onClick={() => setUserData({...userData, role: "brigadist"})}
                  className={`w-full flex items-center justify-between p-5 border rounded-2xl transition-all ${userData.role === "brigadist" ? 'border-blue-500 bg-blue-900/10 ring-1 ring-blue-500' : 'border-gray-800 bg-[#0d0d0d]'}`}
                 >
                    <div className="flex flex-col items-start">
                      <span className={`font-black uppercase text-[11px] ${userData.role === "brigadist" ? 'text-blue-400' : 'text-gray-400'}`}>Brigadista</span>
                      <span className="text-[8px] text-gray-600 font-bold uppercase">Acceso a sistema de captura</span>
                    </div>
                    {userData.role === "brigadist" && <div className="w-2.5 h-2.5 bg-blue-500 rounded-full" />}
                 </button>
              </div>

              {userData.role === "brigadist" && (
                 <div className="space-y-3 p-4 bg-black rounded-2xl border border-gray-900 animate-in fade-in duration-300">
                    <input type="email" placeholder="Email" className={inputClass} onChange={e => setUserData({...userData, email: e.target.value})} required />
                    <input type="password" placeholder="Contraseña" className={inputClass} onChange={e => setUserData({...userData, password: e.target.value})} required />
                 </div>
              )}

              {message && <div className="text-red-500 text-center font-black uppercase text-[10px]">{message}</div>}
              <button type="button" onClick={handleUserSubmit} disabled={loading} className="w-full rounded-xl bg-blue-600 py-4 font-black uppercase text-[11px]">
                {loading ? "GUARDANDO..." : "FINALIZAR REGISTRO"}
              </button>
          </div>
        )}
      </div>
    </div>
  );
}