"use client";

import { useState, useEffect, useRef } from "react";
import { useRouter, useSearchParams } from "next/navigation";
import { UserCheck, UserX, Plus, Edit, Trash2, X, XCircle, AlertTriangle, ChevronDown, Search, Building2, BookOpen } from "lucide-react";
import { toggleUserStatus, createUsuario, updateUsuario, deleteUsuario } from "@/app/actions/usuarios";
import DataTable from "@/components/ui/DataTable";

type Colegio = { id: string; nombre: string };
export type CursoOption = { id: string; titulo: string; colegioId?: string | null };

export type Usuario = {
  id: string; name: string | null; email: string; role: string;
  telefono: string | null; edad: number | null; status: string;
  direccion: string | null; observaciones: string | null;
  representanteNombre: string | null; representanteTelefono: string | null;
  colegioId?: string | null;
  cursoIds?: string[];
};

export default function UsuariosListClient({ usuarios, colegios, cursos }: { usuarios: Usuario[]; colegios?: Colegio[]; cursos: CursoOption[] }) {
  const initialSearch = "";

  const router = useRouter();
  const searchParams = useSearchParams();
  const [loadingId, setLoadingId] = useState<string | null>(null);
  const [showCreate, setShowCreate] = useState(false);
  const [editingUser, setEditingUser] = useState<Usuario | null>(null);
  const [errorMsg, setErrorMsg] = useState("");
  const [successMsg, setSuccessMsg] = useState("");
  const [filtroSede, setFiltroSede] = useState(searchParams.get("colegioId") || "");
  const [filtroRol, setFiltroRol] = useState("");

  const usuariosVisibles = usuarios.filter(u => {
    const matchSede = filtroSede ? u.colegioId === filtroSede : true;
    const matchRol = filtroRol ? u.role === filtroRol : true;
    return matchSede && matchRol;
  });

  const handleToggle = async (id: string, status: string) => {
    if (!confirm(`¿Cambiar solvencia a ${status === "SOLVENTE" ? "MOROSO" : "SOLVENTE"}?`)) return;
    setLoadingId(id);
    await toggleUserStatus(id, status);
    router.refresh();
    setLoadingId(null);
  };

  const handleDelete = async (id: string, name: string | null) => {
    if (!confirm(`¿Ocultar e inhabilitar a ${name}? Esta acción no se puede deshacer de forma fácil.`)) return;
    setLoadingId(id);
    const res = await deleteUsuario(id);
    if (!res.success) setErrorMsg(res.error || "Error al eliminar.");
    else router.refresh();
    setLoadingId(null);
  };

  return (
    <div className="p-8 max-w-7xl mx-auto">
      <div className="flex justify-between items-center mb-8 flex-wrap gap-4">
        <div>
          <h1 className="text-3xl font-extrabold text-gray-800">Gestión de Usuarios</h1>
          <p className="text-gray-500">Gestión de roles, estados y datos de contacto.</p>
        </div>
        <button onClick={() => setShowCreate(true)}
          className="bg-[#0066ff] hover:bg-blue-700 text-white font-bold py-3 px-6 rounded-lg flex items-center gap-2 shadow-sm transition-colors">
          <Plus className="w-5 h-5" /> Agregar Usuario
        </button>
      </div>

      {errorMsg && (
        <div className="bg-red-50 text-red-700 p-4 mb-6 rounded-lg font-semibold flex gap-2 items-center">
          <AlertTriangle className="w-5 h-5 shrink-0" /> {errorMsg}
        </div>
      )}

      {successMsg && (
        <div className="bg-green-50 text-green-700 p-4 mb-6 rounded-lg font-semibold flex gap-2 items-center">
          <UserCheck className="w-5 h-5 shrink-0" /> {successMsg}
        </div>
      )}

      <div className="flex flex-wrap items-center gap-4 mb-6">
        {/* Filtro Sede para SuperAdmin */}
        {colegios && colegios.length > 1 && (
          <div className="bg-white p-4 rounded-xl shadow-sm border border-gray-100 flex items-center gap-4 flex-grow">
            <label className="font-semibold text-gray-700 text-sm whitespace-nowrap">Filtrar por Institución:</label>
            <select value={filtroSede} onChange={e => setFiltroSede(e.target.value)}
              className="border border-gray-200 p-2 rounded-lg focus:ring-2 focus:ring-[#0066ff] outline-none bg-gray-50 text-sm min-w-[200px] w-full">
              <option value="">Todas las Sedes / Colegios</option>
              {colegios.map(c => <option key={c.id} value={c.id}>{c.nombre}</option>)}
            </select>
          </div>
        )}

        {/* Filtro Rol */}
        <div className="bg-white p-4 rounded-xl shadow-sm border border-gray-100 flex items-center gap-4 flex-grow">
          <label className="font-semibold text-gray-700 text-sm whitespace-nowrap">Filtrar por Rol:</label>
          <select value={filtroRol} onChange={e => setFiltroRol(e.target.value)}
            className="border border-gray-200 p-2 rounded-lg focus:ring-2 focus:ring-[#0066ff] outline-none bg-gray-50 text-sm min-w-[200px] w-full">
            <option value="">Todos los Roles</option>
            <option value="ESTUDIANTE">Estudiante</option>
            <option value="PROFESOR">Profesor</option>
            <option value="ADMIN_COLEGIO">Admin Colegio / Sede</option>
            <option value="SUPERADMIN">Super Admin</option>
          </select>
        </div>
      </div>

      <DataTable
        data={usuariosVisibles}
        title="Usuarios"
        exportFilename="usuarios"
        searchPlaceholder="Buscar usuario..."
        searchKeys={["name", "email", "telefono"]}
        defaultSearch={initialSearch}
        pageSize={10}
        columns={[
          { key: "name", label: "Nombre", render: (u: any) => (
            <div>
              <div className="font-bold text-gray-800">{u.name || "Sin nombre"}</div>
              <div className="text-xs text-gray-400">{u.email}</div>
            </div>
          ), exportValue: (u: any) => u.name || "" },
          { key: "role", label: "Rol", render: (u: any) => (
            <span className={`px-2.5 py-1 rounded-full text-xs font-bold ${
              u.role === "SUPERADMIN" ? "bg-red-100 text-red-700" :
              u.role === "ADMIN_COLEGIO" ? "bg-indigo-100 text-indigo-700" :
              u.role === "PROFESOR" ? "bg-purple-100 text-purple-700" :
              "bg-gray-100 text-gray-700"
            }`}>{u.role}</span>
          ) },
          { key: "telefono", label: "Contacto", render: (u: any) => (
            <div className="text-xs text-gray-600 space-y-0.5">
              {u.telefono && <div>📞 {u.telefono}</div>}
              {u.representanteNombre && <div>👨‍👧 {u.representanteNombre}</div>}
            </div>
          ), exportValue: (u: any) => u.telefono || "" },
          { key: "status", label: "Solvencia", render: (u: any) => (
            <button onClick={() => handleToggle(u.id, u.status)} disabled={loadingId === u.id}
              className="transition-all disabled:opacity-50">
              {u.status === "SOLVENTE" ? (
                <span className="inline-flex items-center gap-1.5 px-3 py-1 rounded-full text-xs font-bold bg-green-100 text-green-700 hover:bg-green-200">
                  <UserCheck className="w-3.5 h-3.5" /> Solvente
                </span>
              ) : (
                <span className="inline-flex items-center gap-1.5 px-3 py-1 rounded-full text-xs font-bold bg-red-100 text-red-700 hover:bg-red-200">
                  <UserX className="w-3.5 h-3.5" /> Moroso
                </span>
              )}
            </button>
          ), exportValue: (u: any) => u.status },
        ]}
        actions={(u: any) => (
          <div className="flex justify-end gap-1">
            <button onClick={() => setEditingUser(u)} className="text-blue-500 hover:bg-blue-50 p-2 rounded transition-colors">
              <Edit className="w-4 h-4" />
            </button>
            <button onClick={() => handleDelete(u.id, u.name)} disabled={loadingId === u.id}
              className="text-red-500 hover:bg-red-50 p-2 rounded transition-colors disabled:opacity-50">
              {loadingId === u.id ? <span className="animate-spin block">⟳</span> : <Trash2 className="w-4 h-4" />}
            </button>
          </div>
        )}
      />

      {/* Modal Crear */}
      {showCreate && (
        <Modal title="Nuevo Usuario" onClose={() => setShowCreate(false)}>
          <UserForm colegios={colegios || []} cursos={cursos}
            onSubmit={async (fd) => { 
              const r = await createUsuario(fd); 
              if (r.success) {
                setShowCreate(false);
                setSuccessMsg("El usuario ha sido registrado exitosamente. Se ha enviado el usuario y la clave por correo al registrado y al registrante.");
                router.refresh();
                return { success: true };
              } else {
                return { success: false, error: r.error || "Error" };
              }
            }}
            onCancel={() => setShowCreate(false)} />
        </Modal>
      )}

      {/* Modal Editar */}
      {editingUser && (
        <Modal title={`Editar: ${editingUser.name}`} onClose={() => setEditingUser(null)}>
          <UserForm colegios={colegios || []} cursos={cursos} defaults={editingUser}
            onSubmit={async (fd) => { 
              const r = await updateUsuario(editingUser.id, fd); 
              if (r.success) { 
                setEditingUser(null); 
                router.refresh(); 
                return { success: true };
              } else {
                return { success: false, error: r.error || "Error" };
              }
            }}
            onCancel={() => setEditingUser(null)} />
        </Modal>
      )}
    </div>
  );
}

function UserForm({ colegios, cursos, defaults, onSubmit, onCancel }: {
  colegios: Colegio[]; cursos: CursoOption[]; defaults?: Usuario | null;
  onSubmit: (fd: FormData) => Promise<{ success: boolean; error?: string }>; onCancel: () => void;
}) {
  const [selectedRole, setSelectedRole] = useState(defaults?.role || "ESTUDIANTE");
  const [selectedColegioId, setSelectedColegioId] = useState(
    defaults?.colegioId || (colegios.length === 1 ? colegios[0].id : "")
  );
  const [selectedCursos, setSelectedCursos] = useState<string[]>(defaults?.cursoIds || []);
  const [isSubmitting, setIsSubmitting] = useState(false);
  const [error, setError] = useState("");

  const toggleCurso = (id: string) => setSelectedCursos(prev => prev.includes(id) ? prev.filter(x => x !== id) : [...prev, id]);

  const handleSubmit = async (e: React.FormEvent<HTMLFormElement>) => {
    e.preventDefault();
    setError("");
    setIsSubmitting(true);
    const fd = new FormData(e.currentTarget);
    selectedCursos.forEach(id => fd.append("cursoId", id));
    const res = await onSubmit(fd);
    if (!res.success) {
      setError(res.error || "Error al procesar la solicitud.");
    }
    setIsSubmitting(false);
  };

  // Filter courses based on selected colegio
  const filteredCursos = selectedColegioId 
    ? cursos.filter(c => c.colegioId === selectedColegioId)
    : [];

  return (
    <form onSubmit={handleSubmit} className="space-y-4">
      {error && (
        <div className="bg-red-50 text-red-700 p-3 rounded-lg text-sm font-bold flex gap-2 items-center">
          <AlertTriangle className="w-4 h-4 shrink-0" /> {error}
        </div>
      )}
      <Field label="Nombre Completo" name="name" required defaultValue={defaults?.name || ""} />
      <Field label="Email (Usuario de acceso)" name="email" type="email" required defaultValue={defaults?.email || ""} />
      <div className="grid grid-cols-2 gap-4">
        <Field label="Teléfono" name="telefono" defaultValue={defaults?.telefono || ""} />
        <Field label="Edad" name="edad" type="number" defaultValue={String(defaults?.edad || "")} />
      </div>
      <Field label="Dirección" name="direccion" defaultValue={defaults?.direccion || ""} />
      <div className="grid grid-cols-2 gap-4">
        <Field label="Representante" name="representanteNombre" defaultValue={defaults?.representanteNombre || ""} />
        <Field label="Tel. Representante" name="representanteTelefono" defaultValue={defaults?.representanteTelefono || ""} />
      </div>
      <div className="grid grid-cols-2 gap-4">
        <div>
          <label className="block text-sm font-semibold text-gray-700 mb-1">Rol</label>
          <select name="role" value={selectedRole} onChange={e => setSelectedRole(e.target.value)}
            className="w-full border border-gray-200 p-3 rounded-lg focus:ring-2 focus:ring-[#0066ff] outline-none bg-white">
            <option value="ESTUDIANTE">Estudiante</option>
            <option value="PROFESOR">Profesor</option>
            <option value="ADMIN_COLEGIO">Admin Sede</option>
            <option value="SUPERADMIN">Super Admin</option>
          </select>
        </div>
        {colegios && colegios.length > 0 && selectedRole !== "SUPERADMIN" && (
          <div className="flex-1">
            <SearchableSelect 
              label="Institución / Sede"
              name="colegioId"
              placeholder="-- Seleccionar Sede --"
              value={selectedColegioId || ""}
              options={colegios.map(c => ({ id: c.id, label: c.nombre }))}
              onChange={val => {
                setSelectedColegioId(val);
                setSelectedCursos([]);
              }}
              required={selectedRole !== "SUPERADMIN"}
            />
          </div>
        )}
      </div>
      <div>
        <label className="block text-sm font-semibold text-gray-700 mb-1">Observaciones</label>
        <textarea name="observaciones" rows={2} defaultValue={defaults?.observaciones || ""}
          className="w-full border border-gray-200 p-3 rounded-lg focus:ring-2 focus:ring-[#0066ff] outline-none resize-none" />
      </div>

      {/* Cursos Asociados */}
      <div>
        <label className="block text-sm font-semibold text-gray-700 mb-2">📘 Asignar Cursos</label>
        {filteredCursos.length > 0 ? (
          <div className="border border-gray-200 rounded-lg divide-y divide-gray-100 max-h-48 overflow-y-auto">
            {filteredCursos.map(c => (
              <label key={c.id} className={`flex items-center gap-3 px-4 py-3 cursor-pointer hover:bg-blue-50 transition-colors ${selectedCursos.includes(c.id) ? 'bg-blue-50' : ''}`}>
                <input type="checkbox" checked={selectedCursos.includes(c.id)} onChange={() => toggleCurso(c.id)} className="w-4 h-4 accent-[#0066ff]" />
                <span className="font-semibold text-gray-800 text-sm">{c.titulo}</span>
                {selectedCursos.includes(c.id) && <span className="ml-auto text-[#0066ff] text-xs font-bold">✓</span>}
              </label>
            ))}
          </div>
        ) : (
          <div className="border border-dashed border-gray-200 rounded-lg p-6 text-center text-gray-400 text-sm">
            {selectedColegioId ? "No hay cursos registrados para esta sede." : "Selecciona una sede para ver cursos disponibles."}
          </div>
        )}
      </div>

      <Field 
        label={defaults ? "Nueva Contraseña (dejar en blanco para no cambiar)" : "Contraseña"} 
        name="password" 
        required={!defaults}
        placeholder={defaults ? "Escriba nueva clave..." : "Ej: Estudiante123!"}
      />
      <div className="pt-4 flex justify-end gap-3">
        <button type="button" onClick={onCancel} disabled={isSubmitting} className="px-5 py-3 rounded-lg font-semibold text-gray-600 hover:bg-gray-100 transition-colors disabled:opacity-50">Cancelar</button>
        <button type="submit" disabled={isSubmitting} className="bg-[#1e2a47] hover:bg-[#f04b50] text-white px-6 py-3 rounded-lg font-bold transition-colors shadow-md disabled:opacity-50 flex items-center gap-2">
          {isSubmitting ? <span className="animate-spin block">⟳</span> : null}
          {defaults ? "Guardar Cambios" : "Crear Usuario"}
        </button>
      </div>
    </form>
  );
}

function Modal({ title, onClose, children }: { title: string; onClose: () => void; children: React.ReactNode }) {
  return (
    <div className="fixed inset-0 bg-black/60 backdrop-blur-sm z-[1000] flex items-center justify-center p-4">
      <div className="bg-white rounded-3xl w-full max-w-lg shadow-2xl overflow-hidden max-h-[95vh] flex flex-col">
        <div className="flex justify-between items-center p-6 border-b border-gray-100">
          <h2 className="text-xl font-bold text-gray-800">{title}</h2>
          <button 
            onClick={onClose} 
            className="p-2 rounded-full text-gray-400 hover:bg-gray-100 hover:text-gray-600 transition-all"
            title="Cerrar"
          >
            <X className="w-6 h-6" />
          </button>
        </div>
        <div className="p-8 overflow-y-auto custom-scrollbar">
          {children}
        </div>
      </div>
    </div>
  );
}

function SearchableSelect({ 
  label, 
  options, 
  value: initialValue, 
  onChange, 
  placeholder, 
  required,
  name
}: { 
  label: string; 
  options: { id: string; label: string; icon?: string }[]; 
  value: string; 
  onChange: (val: string) => void;
  placeholder?: string;
  required?: boolean;
  name?: string;
}) {
  const [isOpen, setIsOpen] = useState(false);
  const [search, setSearch] = useState("");
  const [internalValue, setInternalValue] = useState(initialValue);
  const containerRef = useRef<HTMLDivElement>(null);

  useEffect(() => {
    setInternalValue(initialValue);
  }, [initialValue]);

  const filtered = options.filter(o => 
    o.label.toLowerCase().includes(search.toLowerCase())
  );

  const selected = options.find(o => o.id === internalValue);

  useEffect(() => {
    const handleClick = (e: MouseEvent) => {
      if (containerRef.current && !containerRef.current.contains(e.target as Node)) {
        setIsOpen(false);
      }
    };
    document.addEventListener("mousedown", handleClick);
    return () => document.removeEventListener("mousedown", handleClick);
  }, []);

  return (
    <div className="relative" ref={containerRef}>
      <label className="block text-sm font-semibold text-gray-700 mb-1">{label} {required && "*"}</label>
      <div 
        onClick={() => setIsOpen(!isOpen)}
        className={`w-full border border-gray-200 p-3 rounded-lg flex justify-between items-center transition-all bg-white cursor-pointer ${isOpen ? 'ring-2 ring-blue-500 border-blue-500' : 'hover:border-gray-300 shadow-sm'}`}
      >
        <span className={`truncate ${selected ? "text-gray-800 font-medium" : "text-gray-400"}`}>
          {selected ? (selected.icon ? `${selected.icon} ${selected.label}` : selected.label) : (placeholder || "-- Seleccionar --")}
        </span>
        <ChevronDown className={`w-4 h-4 text-gray-400 transition-transform duration-200 ${isOpen ? 'rotate-180' : ''}`} />
      </div>
      <input type="hidden" name={name} value={internalValue} required={required} />
      
      {isOpen && (
        <div className="absolute z-[1100] w-full mt-1 bg-white border border-gray-200 rounded-xl shadow-2xl overflow-hidden animate-in fade-in slide-in-from-top-2 duration-200">
          <div className="p-3 border-b border-gray-100 bg-gray-50/50">
            <div className="relative">
              <Search className="absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-gray-400" />
              <input 
                autoFocus
                type="text" 
                placeholder="Buscar..." 
                value={search}
                onChange={e => setSearch(e.target.value)}
                className="w-full pl-10 pr-4 py-2 text-sm border border-gray-200 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-blue-500 outline-none transition-all"
              />
            </div>
          </div>
          <div className="max-h-64 overflow-y-auto p-1">
            {filtered.length > 0 ? (
              filtered.map(opt => (
                <div 
                  key={opt.id}
                  onClick={() => { 
                    setInternalValue(opt.id);
                    onChange(opt.id); 
                    setIsOpen(false); 
                    setSearch(""); 
                  }}
                  className={`flex items-center gap-3 px-4 py-2.5 rounded-lg cursor-pointer transition-all mb-0.5 ${internalValue === opt.id ? 'bg-blue-600 text-white shadow-md' : 'hover:bg-blue-50 text-gray-700'}`}
                >
                  {opt.icon && <span className="text-lg">{opt.icon}</span>}
                  <span className="text-[14px] font-semibold">{opt.label}</span>
                </div>
              ))
            ) : (
              <div className="p-4 text-center text-gray-400 text-sm">No hay resultados</div>
            )}
          </div>
        </div>
      )}
    </div>
  );
}

function Field({ label, name, required, type = "text", defaultValue = "", placeholder }: {
  label: string; name: string; required?: boolean; type?: string; defaultValue?: string; placeholder?: string;
}) {
  return (
    <div>
      <label className="block text-sm font-semibold text-gray-700 mb-1">{label}</label>
      <input required={required} name={name} type={type} defaultValue={defaultValue} placeholder={placeholder}
        className="w-full border border-gray-200 p-3 rounded-lg focus:ring-2 focus:ring-[#0066ff] outline-none" />
    </div>
  );
}
