"use client";

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

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

export default function BrigadistCreateMilitantPage() {
  const router = useRouter();
  const [loading, setLoading] = useState(false);
  const [message, setMessage] = useState("");
  const [coloniasDisponibles, setColoniasDisponibles] = useState<Section[]>([]);

  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: "",
    // Campos de ubicación automática
    latitude: null as number | null,
    longitude: null as number | null,
  });

  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";

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

  // --- ALGORITMO NATIVO 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;
      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 handleSubmit(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 el registro");
      
      if (data.id) {
        localStorage.setItem("last_militant_id", data.id.toString());
        // El brigadista termina aquí y va directo a la foto
        router.push(`/brigadist/militants/upload-ine?id=${data.id}`);
      }
    } 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 flex items-center justify-between">
          <Link href="/brigadist/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 italic">Panel</span>
          </Link>
          <div className="flex items-center gap-1 text-green-500 animate-pulse">
            <Navigation size={12} />
            <span className="text-[8px] font-black uppercase tracking-widest">GPS Activo</span>
          </div>
        </header>

        <header className="mb-8">
            <h1 className="text-3xl font-black italic uppercase leading-none tracking-tighter">Captura <span className="text-blue-500 underline decoration-blue-500/30 underline-offset-4">Territorial</span></h1>
            <p className="text-[9px] text-gray-500 font-bold uppercase mt-2 tracking-widest">Zapata Morelos Unit</p>
        </header>

        <form onSubmit={handleSubmit} className="space-y-6 pb-24">
          
          {/* IDENTIDAD */}
          <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-sm font-black uppercase italic text-white tracking-widest">Datos Ciudadanos</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-2 gap-4">
                  <div className="flex flex-col gap-1.5 w-full">
                    <label className="text-[8px] font-black text-gray-600 uppercase ml-2 italic">Fecha 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-[8px] font-black text-gray-600 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>
          </div>

          {/* VALIDACIÓN */}
          <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-sm font-black uppercase italic text-white tracking-widest">Oficiales</h2></div>
            <div className="space-y-4">
              <div className="space-y-1">
                <label className="text-[8px] font-black text-blue-400 uppercase ml-2">CURP (Auto-generada)</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 />
              <div className="flex items-center gap-2">
                <Smartphone size={16} className="text-gray-600" />
                <input name="phone" placeholder="Celular" value={form.phone} onChange={handleInputChange} className={inputClass} />
              </div>
            </div>
          </div>

          {/* TERRITORIO */}
          <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-sm font-black uppercase italic text-white tracking-widest">Localización</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>
              <textarea name="reference_text" placeholder="Referencias de la vivienda..." value={form.reference_text} onChange={handleInputChange} className={`${inputClass} h-16 resize-none`} />
              <textarea name="notes" placeholder="Observaciones adicionales..." value={form.notes} onChange={handleInputChange} className={`${inputClass} h-16 resize-none`} />
            </div>
          </div>

          <div className="flex flex-col items-center gap-4 py-4">
            {message && <div className="w-full p-3 rounded-xl border border-red-500/30 bg-red-500/10 text-red-400 text-[9px] font-black uppercase text-center">{message}</div>}
            <button type="submit" disabled={loading} className="w-full rounded-2xl bg-white text-black py-4 text-xs font-black uppercase italic tracking-widest shadow-[0_10px_30px_rgba(255,255,255,0.1)] active:scale-95 transition-all">
              {loading ? "Sincronizando..." : "Finalizar Captura y Subir INE"}
            </button>
          </div>
        </form>
      </div>
    </div>
  );
}