"use client";

import { useState, useEffect } from "react";
import {
  Search,
  User,
  HardHat,
  MapPin,
  Phone,
  ArrowLeft,
  MessageCircle,
  Edit3,
  X,
  Send,
  Eye,
  BookOpenCheck,
  Smartphone,
  ChevronDown,
  ChevronRight,
  UserMinus,
  UserCheck,
  Power,
  Database,
} from "lucide-react";
import Link from "next/link";

export default function LeaderStructurePage() {
  const [structure, setStructure] = useState<any[]>([]);
  const [loading, setLoading] = useState(true);
  const [expandedBrigadist, setExpandedBrigadist] = useState<number | null>(
    null,
  );

  // Modales
  const [showEditModal, setShowEditModal] = useState(false);
  const [showReviewModal, setShowReviewModal] = useState(false);
  const [selectedMilitant, setSelectedMilitant] = useState<any>(null);
  const [reviewText, setReviewText] = useState("");
  const [coloniasEdit, setColoniasEdit] = useState<any[]>([]);

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

  const fetchStructure = async () => {
    setLoading(true);
    try {
      const res = await fetch(`/api/leader/structure`);
      const data = await res.json();
      setStructure(Array.isArray(data) ? data : []);
    } catch (err) {
      console.error(err);
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    fetchStructure();
  }, []);

  // Lógica de carga de colonias
  useEffect(() => {
    if (selectedMilitant?.postal_code?.length === 5) {
      fetch(`/api/sections?cp=${selectedMilitant.postal_code}`)
        .then((res) => res.json())
        .then((data) => setColoniasEdit(Array.isArray(data) ? data : []));
    }
  }, [selectedMilitant?.postal_code]);

  const handleEditChange = (e: any) => {
    const { name, value } = e.target;
    setSelectedMilitant((prev: any) => ({ ...prev, [name]: value }));
  };

  const handleUpdate = async () => {
    try {
      const res = await fetch(`/api/brigadist/update`, {
        method: "PUT",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify(selectedMilitant),
      });
      if (res.ok) {
        setShowEditModal(false);
        fetchStructure();
      }
    } catch (error) {
      console.error(error);
    }
  };

  const handleToggle = async (
    id: number,
    type: "brigadist" | "militant",
    currentStatus: any,
  ) => {
    const action =
      currentStatus === true || currentStatus === "active"
        ? "INHABILITAR"
        : "HABILITAR";
    if (!confirm(`¿Estás seguro de que deseas ${action} a este ${type}?`))
      return;

    const endpoint =
      type === "brigadist"
        ? "/api/users/toggle-status"
        : "/api/militants/toggle-status";
    const newStatus =
      type === "brigadist"
        ? !currentStatus
        : currentStatus === "active"
          ? "inactive"
          : "active";

    await fetch(endpoint, {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({ id, status: newStatus }),
    });
    fetchStructure();
  };

  const handleReview = async () => {
    if (!reviewText.trim()) return alert("Escribe el motivo de la revisión");

    const isBrigadist = selectedMilitant.hasOwnProperty("militantes");
    const endpoint = isBrigadist
      ? "/api/leader/suspend-brigadist"
      : "/api/brigadist/review";

    try {
      const res = await fetch(endpoint, {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({
          id: selectedMilitant.id,
          notes: reviewText,
          status: "review",
        }),
      });

      if (res.ok) {
        setShowReviewModal(false);
        setReviewText("");
        fetchStructure();
        alert(
          isBrigadist
            ? "Acceso de brigadista suspendido y enviado a revisión."
            : "Militante enviado a revisión.",
        );
      }
    } catch (error) {
      console.error(error);
      alert("Error al procesar la solicitud");
    }
  };

  return (
    <div className="min-h-screen bg-[#050505] text-white p-4 md:p-10 font-sans overflow-x-hidden">
      <header className="mb-8 md:mb-10 flex justify-between items-end">
        <div className="space-y-4 w-full">
          <Link
            href="/leader/dashboard"
            className="text-purple-500 flex items-center gap-2 text-[10px] font-black uppercase tracking-widest hover:opacity-70 transition-all"
          >
            <ArrowLeft size={16} /> Volver al Panel
          </Link>
          <h1 className="text-3xl md:text-4xl font-black uppercase italic tracking-tighter leading-tight">
            Red de <span className="text-purple-500">Estructura</span>
          </h1>
        </div>
      </header>

      {loading ? (
        <div className="p-20 text-center animate-pulse text-gray-600 uppercase text-[10px] tracking-[0.3em]">
          Mapeando jerarquía de brigadistas...
        </div>
      ) : (
        <div className="space-y-6 max-w-5xl mx-auto pb-10">
          {structure.map((brig) => (
            <div
              key={brig.id}
              className="bg-[#0a0a0a] border border-gray-900 rounded-3xl md:rounded-[2.5rem] overflow-hidden shadow-2xl transition-all"
            >
              {/* Header Brigadista Adaptado */}
              <div
                className="p-5 md:p-8 cursor-pointer hover:bg-white/[0.01] transition-all"
                onClick={() =>
                  setExpandedBrigadist(
                    expandedBrigadist === brig.id ? null : brig.id,
                  )
                }
              >
                <div className="flex flex-col md:flex-row md:items-center justify-between gap-6">
                  <div className="flex items-center gap-4 md:gap-5">
                    <div
                      className={`p-3 md:p-4 rounded-2xl shrink-0 ${brig.active ? "bg-purple-500/10 text-purple-500" : "bg-red-500/10 text-red-500"}`}
                    >
                      <HardHat size={24} className="md:w-7 md:h-7" />
                    </div>
                    <div className="min-w-0">
                      <h3 className="text-base md:text-lg font-black uppercase italic leading-tight truncate">
                        {brig.full_name}
                      </h3>
                      <span className="text-[9px] font-black text-gray-500 uppercase tracking-widest block mt-1">
                        {brig.militantes.length} Integrantes Asignados
                      </span>
                    </div>
                  </div>

                  <div
                    className="flex items-center justify-between md:justify-end gap-3 border-t border-gray-900 pt-4 md:border-t-0 md:pt-0"
                    onClick={(e) => e.stopPropagation()}
                  >
                    <div className="flex items-center gap-2">
                      <button
                        onClick={() => {
                          setSelectedMilitant(brig);
                          setShowReviewModal(true);
                        }}
                        className="p-3 text-gray-600 hover:text-yellow-500 border border-gray-900 rounded-xl transition-all"
                        title="Revisión"
                      >
                        <Eye size={18} />
                      </button>
                      <button
                        onClick={() =>
                          handleToggle(brig.id, "brigadist", brig.active)
                        }
                        className={`px-4 py-2.5 rounded-xl text-[9px] font-black uppercase border transition-all ${brig.active ? "border-emerald-500/20 text-emerald-500 bg-emerald-500/5" : "border-red-500/20 text-red-500 bg-red-500/5"}`}
                      >
                        {brig.active ? "Acceso Activo" : "Acceso Denegado"}
                      </button>
                    </div>
                    {expandedBrigadist === brig.id ? (
                      <ChevronDown size={20} className="text-gray-600 shrink-0" />
                    ) : (
                      <ChevronRight size={20} className="text-gray-600 shrink-0" />
                    )}
                  </div>
                </div>
              </div>

              {/* Hijos (Militantes) Adaptados */}
              {expandedBrigadist === brig.id && (
                <div className="px-4 md:px-8 pb-6 md:pb-8 animate-in slide-in-from-top-2 duration-300">
                  <div className="md:ml-10 border-l-2 border-gray-900 pl-4 md:pl-8 space-y-4">
                    {brig.militantes.length === 0 ? (
                      <p className="text-[10px] text-gray-600 font-black uppercase py-4">
                        Sin registros.
                      </p>
                    ) : (
                      brig.militantes.map((m: any) => (
                        <div
                          key={m.id}
                          className="bg-[#050505] border border-gray-800 p-4 md:p-5 rounded-2xl md:rounded-3xl flex flex-col md:flex-row md:items-center justify-between gap-4 group hover:border-purple-500/40 transition-all"
                        >
                          <div className="flex items-center gap-4">
                            <div
                              className={`w-9 h-9 md:w-10 md:h-10 shrink-0 rounded-full flex items-center justify-center ${m.status === "review" ? "bg-yellow-500/10 text-yellow-500 border border-yellow-500/20" : "bg-gray-900 text-gray-500"}`}
                            >
                              <User size={16} />
                            </div>
                            <div className="min-w-0">
                              <h4 className="text-xs md:text-sm font-bold uppercase tracking-tight truncate">
                                {m.first_name} {m.last_name_paternal}
                              </h4>
                              <p className="text-[9px] md:text-[10px] font-mono text-gray-600 uppercase mt-0.5">
                                {m.curp}
                              </p>
                            </div>
                          </div>

                          <div className="flex items-center justify-between md:justify-end gap-1 bg-[#0a0a0a] md:bg-transparent p-2 md:p-0 rounded-xl">
                            <a
                              href={`tel:${m.phone}`}
                              className="p-2.5 text-gray-600 hover:text-blue-500"
                            >
                              <Phone size={14} />
                            </a>
                            <a
                              href={`https://wa.me/52${m.phone}`}
                              target="_blank"
                              className="p-2.5 text-gray-600 hover:text-emerald-500"
                            >
                              <MessageCircle size={14} />
                            </a>
                            <button
                              onClick={() => {
                                setSelectedMilitant(m);
                                setShowEditModal(true);
                              }}
                              className="p-2.5 text-gray-600 hover:text-blue-500"
                            >
                              <Edit3 size={14} />
                            </button>
                            <button
                              onClick={() => {
                                setSelectedMilitant(m);
                                setShowReviewModal(true);
                              }}
                              className="p-2.5 text-gray-600 hover:text-yellow-500"
                            >
                              <Eye size={14} />
                            </button>
                            <button
                              onClick={() =>
                                handleToggle(m.id, "militant", m.status)
                              }
                              className={`p-2.5 ${m.status === "active" ? "text-emerald-500" : "text-red-500"}`}
                            >
                              <Power size={14} />
                            </button>
                          </div>
                        </div>
                      ))
                    )}
                  </div>
                </div>
              )}
            </div>
          ))}
        </div>
      )}

      {/* MODALES IGUALES PERO CON PADDING ADAPTADO */}
      {showEditModal && selectedMilitant && (
        <div className="fixed inset-0 z-[200] flex items-center justify-center p-4 bg-black/95 backdrop-blur-md">
          <div className="bg-[#050505] border border-gray-900 w-full max-w-lg rounded-[2rem] md:rounded-[2.5rem] p-6 md:p-8 shadow-2xl relative">
            <header className="flex justify-between items-center mb-6">
              <h3 className="text-xl md:text-2xl font-black uppercase italic">
                Corregir <span className="text-purple-500">Militante</span>
              </h3>
              <button
                onClick={() => setShowEditModal(false)}
                className="bg-red-500/10 text-red-500 p-2 rounded-full"
              >
                <X size={20} />
              </button>
            </header>

            <div className="space-y-6 max-h-[60vh] overflow-y-auto pr-2 custom-scrollbar pb-4">
              <div className="bg-[#0a0a0a] border border-gray-900 rounded-[1.5rem] p-5 space-y-4">
                <input
                  name="first_name"
                  value={selectedMilitant.first_name || ""}
                  onChange={handleEditChange}
                  className={inputClass}
                  placeholder="Nombre"
                />
                <div className="grid grid-cols-2 gap-3">
                  <input
                    name="last_name_paternal"
                    value={selectedMilitant.last_name_paternal || ""}
                    onChange={handleEditChange}
                    className={inputClass}
                    placeholder="Paterno"
                  />
                  <input
                    name="last_name_maternal"
                    value={selectedMilitant.last_name_maternal || ""}
                    onChange={handleEditChange}
                    className={inputClass}
                    placeholder="Materno"
                  />
                </div>
                <input
                  name="curp"
                  value={selectedMilitant.curp || ""}
                  onChange={handleEditChange}
                  className={`${inputClass} font-mono uppercase text-yellow-500`}
                  placeholder="CURP"
                />
                <input
                  name="phone"
                  value={selectedMilitant.phone || ""}
                  onChange={handleEditChange}
                  className={inputClass}
                  placeholder="Teléfono"
                />
              </div>
              {/* Más campos si son necesarios */}
            </div>

            <button
              onClick={handleUpdate}
              className="w-full mt-6 bg-white text-black h-14 md:h-16 rounded-2xl font-black uppercase text-[10px] md:text-[11px] tracking-widest"
            >
              Sincronizar y Guardar
            </button>
          </div>
        </div>
      )}

      {showReviewModal && (
        <div className="fixed inset-0 z-[200] flex items-center justify-center p-4 bg-black/95 backdrop-blur-md">
          <div className="bg-[#0a0a0a] border border-gray-900 w-full max-w-sm rounded-[2rem] p-6 md:p-8 shadow-2xl">
            <h3 className="text-lg md:text-xl font-black uppercase italic mb-6">
              Solicitar <span className="text-yellow-500">Revisión</span>
            </h3>

            <textarea
              value={reviewText}
              onChange={(e) => setReviewText(e.target.value)}
              placeholder="Explica el motivo..."
              className="w-full bg-[#050505] border border-gray-800 rounded-2xl p-4 text-[11px] text-white h-32 md:h-44 mb-6 resize-none outline-none focus:border-yellow-500"
            />

            <div className="grid grid-cols-2 gap-3">
              <button
                onClick={() => {
                  setShowReviewModal(false);
                  setReviewText("");
                }}
                className="bg-gray-900 text-gray-500 h-12 md:h-14 rounded-2xl font-black uppercase text-[9px] tracking-widest border border-gray-800"
              >
                Cerrar
              </button>
              <button
                onClick={handleReview}
                className="bg-yellow-600 text-black h-12 md:h-14 rounded-2xl font-black uppercase text-[9px] tracking-widest"
              >
                <Send size={12} className="inline mr-2" /> Enviar
              </button>
            </div>
          </div>
        </div>
      )}
    </div>
  );
}