"use client";

import { useState } from "react";
import { useRouter, useSearchParams } from "next/navigation";
import { Trash2, Edit, Plus, XCircle, AlertTriangle, MessageSquare, Send, CheckCircle2 } from "lucide-react";
import { deleteInstructor, createInstructor, updateInstructor } from "@/app/actions/instructores";
import DataTable from "@/components/ui/DataTable";

type CursoOption = { id: string; titulo: string; colegioId: string };
type ColegioOption = { id: string; nombre: string; };
type Instructor = {
  id: string; name: string | null; email: string;
  telefono: string | null; clases: {id: string}[];
  status: string; direccion: string | null; observaciones: string | null;
  cursoIds: string[]; cursoNombres: string[];
  chatConversaciones?: any[];
  colegioId?: string | null;
};

export default function InstructoresListClient({
  instructores, cursos, colegios, userId
}: { instructores: Instructor[]; cursos: CursoOption[]; colegios: ColegioOption[]; userId: string }) {
  const router = useRouter();
  const searchParams = useSearchParams();
  const [loadingId, setLoadingId] = useState<string | null>(null);
  const [showCreateModal, setShowCreateModal] = useState(false);
  const [editingInst, setEditingInst] = useState<Instructor | null>(null);
  const [chattingInst, setChattingInst] = useState<Instructor | null>(null);
  const [errorMsg, setErrorMsg] = useState("");
  const [chatMessage, setChatMessage] = useState("");
  const [filtroSede, setFiltroSede] = useState(searchParams.get("colegioId") || "");

  const instructoresVisibles = filtroSede ? instructores.filter(i => i.colegioId === filtroSede) : instructores;
  const activeChatInst = chattingInst ? instructores.find(i => i.id === chattingInst.id) || chattingInst : null;

  const handleSendChat = async (e: React.FormEvent) => {
    e.preventDefault();
    if (!chatMessage.trim() || !chattingInst) return;
    const { sendMessage, createConversacion } = await import("@/app/actions/chat");
    let conv = chattingInst.chatConversaciones?.[0];
    if (!conv) {
      // Create it if missed
      const ensured = await createConversacion(chattingInst.id, chattingInst.colegioId || "");
      if (!ensured.success || !ensured.conversacionId) return;
      conv = { id: ensured.conversacionId };
    }
    await sendMessage(conv.id, chatMessage);
    setChatMessage("");
    // Note: To see updates immediately, a revalidation or state update is needed.
    // The server action revalidates the chat route.
  };

  const handleDelete = async (id: string, clCount: number) => {
    if (clCount > 0) { alert("Operación bloqueada: Instructor con clases asociadas."); return; }
    if (confirm("¿Ocultar e inhabilitar este instructor?")) {
      setLoadingId(id);
      const res = await deleteInstructor(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 flex-wrap justify-between items-start gap-4 mb-8">
        <div>
          <h1 className="text-3xl font-extrabold text-gray-800">Instructores (Plantilla)</h1>
          <p className="text-gray-500">Gestión de profesores verificados del sistema.</p>
        </div>
        <button onClick={() => setShowCreateModal(true)}
          className="shrink-0 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 Profesor
        </button>
      </div>

      {errorMsg && (
        <div className="bg-red-50 text-red-700 p-4 mb-6 rounded-lg font-semibold flex gap-2">
          <AlertTriangle className="w-5 h-5"/> {errorMsg}
        </div>
      )}

      {/* Filtro Sede para SuperAdmin */}
      {colegios.length > 1 && (
        <div className="mb-6 bg-white p-4 rounded-xl shadow-sm border border-gray-100 flex items-center gap-4">
          <label className="font-semibold text-gray-700 text-sm">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-[250px]">
            <option value="">Todas las Sedes / Colegios</option>
            {colegios.map(c => <option key={c.id} value={c.id}>{c.nombre}</option>)}
          </select>
        </div>
      )}

      <DataTable
        data={instructoresVisibles}
        title="Instructores"
        exportFilename="instructores"
        searchPlaceholder="Buscar instructor..."
        searchKeys={["name", "email"]}
        pageSize={10}
        columns={[
          { key: "name", label: "Nombre", render: (inst: any) => (
            <div>
              <div className="font-bold text-gray-800 text-[15px]">{inst.name}</div>
              <div className="text-xs text-gray-400">{inst.email}</div>
            </div>
          ), exportValue: (inst: any) => inst.name || "" },
          { key: "telefono", label: "Contacto", render: (inst: any) => (
            <div className="text-xs text-gray-600 space-y-0.5">
              {inst.telefono && <div>📞 {inst.telefono}</div>}
              {inst.direccion && <div>📍 {inst.direccion}</div>}
            </div>
          ), exportValue: (inst: any) => inst.telefono || "" },
          { key: "cursoNombres", label: "Cursos Asignados", render: (inst: any) => (
            inst.cursoNombres.length > 0 ? (
              <div className="flex flex-wrap gap-1">
                {inst.cursoNombres.map((n: string) => (
                  <span key={n} className="bg-blue-50 text-blue-700 text-[10px] font-bold px-2 py-0.5 rounded-full">📘 {n}</span>
                ))}
              </div>
            ) : <span className="text-gray-400 text-xs">Sin cursos</span>
          ), exportValue: (inst: any) => inst.cursoNombres.join(", ") },
          { key: "status", label: "Estado", render: (inst: any) => (
            inst.status === "SOLVENTE" || inst.status === "ACTIVO" ? (
              <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">✅ Activo</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">❌ Inactivo</span>
            )
          ), exportValue: (inst: any) => inst.status === "SOLVENTE" ? "Activo" : "Inactivo" },
        ]}
        actions={(inst: any) => {
          const unreads = inst.chatConversaciones?.[0]?.mensajes?.filter((m: any) => !m.read && m.senderId === inst.id).length || 0;
          return (
            <div className="flex justify-end gap-2">
              <button 
                onClick={() => setChattingInst(inst)} 
                className={`relative p-2 rounded transition-colors ${unreads > 0 ? 'text-[#f04b50] hover:bg-red-50 bg-red-50/50' : 'text-[#0066ff] hover:bg-blue-50'}`} 
                title="Chat con Instructor"
              >
                <MessageSquare className={`w-4 h-4 ${unreads > 0 ? 'fill-red-100' : ''}`} />
                {unreads > 0 && (
                  <span className="absolute -top-1 -right-1 flex h-4 w-4 items-center justify-center rounded-full bg-[#f04b50] text-[9px] font-bold text-white shadow-sm ring-2 ring-white">
                    {unreads > 9 ? '9+' : unreads}
                  </span>
                )}
              </button>
              <button onClick={() => setEditingInst(inst)} className="text-blue-500 hover:bg-blue-50 p-2 rounded transition-colors" title="Editar">
                <Edit className="w-4 h-4" />
              </button>
              <button onClick={() => handleDelete(inst.id, inst.clases.length)} disabled={loadingId === inst.id}
                className="text-red-500 hover:bg-red-50 p-2 rounded transition-colors disabled:opacity-50">
                {loadingId === inst.id ? <span className="animate-spin block">⟳</span> : <Trash2 className="w-4 h-4" />}
              </button>
            </div>
          );
        }}
      />

      {/* Modal Crear */}
      {showCreateModal && (
        <Modal title="Alta de Profesor" onClose={() => setShowCreateModal(false)}>
          <InstructorForm cursos={cursos} colegios={colegios}
            onSubmit={async (fd) => { 
              const r = await createInstructor(fd); 
              if (r.success) {
                setShowCreateModal(false); 
                router.refresh();
                return { success: true };
              } else {
                return { success: false, error: r.error || "Error" };
              }
            }}
            onCancel={() => setShowCreateModal(false)} />
        </Modal>
      )}

      {/* Modal Editar */}
      {editingInst && (
        <Modal title={`Editar: ${editingInst.name}`} onClose={() => setEditingInst(null)}>
          <InstructorForm cursos={cursos} colegios={colegios} defaults={editingInst} isEdit
            onSubmit={async (fd) => { 
              const r = await updateInstructor(editingInst.id, fd); 
              if (r.success) {
                setEditingInst(null); 
                router.refresh(); 
                return { success: true };
              } else {
                return { success: false, error: r.error || "Error" };
              }
            }}
            onCancel={() => setEditingInst(null)} />
        </Modal>
      )}

      {/* Modal Chat del Admin */}
      {activeChatInst && chattingInst && (
        <Modal title={`Chat con ${activeChatInst.name}`} onClose={() => setChattingInst(null)}>
          <div className="flex flex-col h-96 bg-gray-50 border border-gray-200 rounded-lg overflow-hidden">
            <div className="flex-1 overflow-y-auto p-4 space-y-4">
              {!activeChatInst.chatConversaciones?.[0]?.mensajes?.length ? (
                <p className="text-center text-xs text-gray-400 mt-10">Sin mensajes de este instructor.</p>
              ) : (
                activeChatInst.chatConversaciones[0].mensajes.map((m: any, i: number) => {
                  const soyAdmin = m.senderId === userId || m.senderId !== activeChatInst.id;
                  return (
                    <div key={i} className={`flex flex-col ${soyAdmin ? 'items-end' : 'items-start'}`}>
                      <div className={`px-4 py-2.5 rounded-2xl max-w-[85%] text-sm shadow-sm ${soyAdmin ? 'bg-[#1e2a47] text-white rounded-br-none' : 'bg-white text-gray-800 border border-gray-200 rounded-bl-none'}`}>
                        {m.contenido}
                      </div>
                      <div className="flex items-center gap-1 mt-1 text-[10px] text-gray-400">
                        {new Date(m.createdAt).toLocaleTimeString([], {hour:'2-digit', minute:'2-digit'})}
                      </div>
                    </div>
                  );
                })
              )}
            </div>
            <form onSubmit={handleSendChat} className="p-3 border-t border-gray-200 bg-white flex gap-2">
              <input type="text" value={chatMessage} onChange={e => setChatMessage(e.target.value)} 
                placeholder="Escribir al instructor..." className="flex-1 text-sm border border-gray-200 rounded-full px-4 outline-none focus:ring-1 focus:ring-[#0066ff]"/>
              <button type="submit" className="w-10 h-10 bg-[#0066ff] hover:bg-blue-600 text-white rounded-full flex items-center justify-center">
                <Send className="w-4 h-4 ml-0.5" />
              </button>
            </form>
          </div>
        </Modal>
      )}
    </div>
  );
}

// ─── Formulario ──────────────────────────────────────────────────────────────
function InstructorForm({ cursos, colegios, defaults, isEdit, onSubmit, onCancel }: {
  cursos: CursoOption[]; colegios: ColegioOption[]; defaults?: Instructor | null; isEdit?: boolean;
  onSubmit: (fd: FormData) => Promise<{ success: boolean; error?: string }>; onCancel: () => void;
}) {
  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 cursosFiltrados = selectedColegioId ? cursos.filter(c => c.colegioId === selectedColegioId) : [];

  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 guardar el instructor.");
    }
    setIsSubmitting(false);
  };

  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>
      )}
      {colegios.length > 0 && (
        <div>
          <label className="block text-sm font-semibold text-gray-700 mb-1">Colegio (Opcional si es global)</label>
          <select name="colegioId" value={selectedColegioId || ""} onChange={e => {
            setSelectedColegioId(e.target.value);
            setSelectedCursos([]); // Limpiar cursos si cambia de colegio
          }}
            className="w-full border border-gray-200 p-3 rounded-lg focus:ring-2 focus:ring-[#0066ff] outline-none bg-white">
            <option value="">-- Sin Colegio (Global) --</option>
            {colegios.map(c => <option key={c.id} value={c.id}>{c.nombre}</option>)}
          </select>
        </div>
      )}
      <Field label="Nombre Completo" name="name" required defaultValue={defaults?.name || ""} />
      <Field label="Email" name="email" type="email" required defaultValue={defaults?.email || ""} />
      <Field label="Teléfono" name="telefono" defaultValue={defaults?.telefono || ""} />
      <Field label="Dirección" name="direccion" defaultValue={defaults?.direccion || ""} />
      <div>
        <label className="block text-sm font-semibold text-gray-700 mb-1">Estatus</label>
        <select name="status" defaultValue={defaults?.status || "SOLVENTE"}
          className="w-full border border-gray-200 p-3 rounded-lg focus:ring-2 focus:ring-[#0066ff] outline-none bg-white">
          <option value="SOLVENTE">✅ Activo</option>
          <option value="MOROSO">❌ Inactivo</option>
        </select>
      </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>
      {!isEdit && <Field label="Contraseña Temporal" name="password" defaultValue="Profesor2025!" />}

      {/* Cursos */}
      <div>
        <label className="block text-sm font-semibold text-gray-700 mb-2">📘 Cursos asignados <span className="text-gray-400 font-normal text-xs">({cursosFiltrados.length} disponibles)</span></label>
        {cursosFiltrados.length > 0 ? (
          <div className="border border-gray-200 rounded-lg divide-y divide-gray-100 max-h-48 overflow-y-auto">
            {cursosFiltrados.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">No hay cursos registrados para este colegio.</div>}
      </div>

      <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}
          {isEdit ? "Guardar Cambios" : "Guardar"}
        </button>
      </div>
    </form>
  );
}

function Modal({ title, onClose, children }: { title: string; onClose: () => void; children: React.ReactNode }) {
  return (
    <div className="fixed inset-0 bg-black/50 backdrop-blur-sm z-[100] flex items-center justify-center p-4">
      <div className="bg-white rounded-2xl w-full max-w-lg shadow-2xl p-8 max-h-[90vh] overflow-y-auto">
        <div className="flex justify-between items-center mb-6">
          <h2 className="text-xl font-bold text-gray-800">{title}</h2>
          <button onClick={onClose} className="text-gray-400 hover:text-gray-600"><XCircle className="w-6 h-6" /></button>
        </div>
        {children}
      </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>
  );
}
