"use client";

import { useState } from "react";
import { useRouter } from "next/navigation";
import { Trash2, Edit, Plus, CheckCircle, XCircle, Building2, AlertTriangle, Users, UserCircle } from "lucide-react";
import { toggleColegioStatus, createColegio, updateColegio, deleteColegio } from "@/app/actions/colegios";
import DataTable from "@/components/ui/DataTable";
import Link from "next/link";

type Colegio = {
  id: string; nombre: string; ubicacion: string | null;
  email: string | null; whatsapp: string | null; telefono: string | null;
  activo: boolean; logoUrl: string | null; color: string | null;
  requisitosInscripcion: string | null;
};

const COLORES_PRESET = [
  "#1e2a47", "#f04b50", "#0066ff", "#00c99f",
  "#7c3aed", "#f59e0b", "#0891b2", "#dc2626",
  "#16a34a", "#ea580c", "#db2777", "#64748b",
];

export default function SedesListClient({ colegios }: { colegios: Colegio[] }) {
  const router = useRouter();
  const [loadingId, setLoadingId]           = useState<string | null>(null);
  const [showCreateModal, setShowCreateModal] = useState(false);
  const [editingColegio, setEditingColegio] = useState<Colegio | null>(null);

  const handleToggle = async (id: string, currentStatus: boolean) => {
    if (!confirm(`¿Estás seguro de ${currentStatus ? 'DESACTIVAR' : 'ACTIVAR'} esta sede?`)) return;
    setLoadingId(id);
    const res = await toggleColegioStatus(id, !currentStatus);
    if (!res.success) alert(res.error);
    router.refresh();
    setLoadingId(null);
  };

  const handleDelete = async (id: string) => {
    if (!confirm("¿Estás seguro de ELIMINAR PERMANENTEMENTE esta sede? Esta acción no se puede deshacer.")) return;
    setLoadingId(id);
    const res = await deleteColegio(id);
    if (!res.success) {
      alert(res.error);
    } else {
      router.refresh();
    }
    setLoadingId(null);
  };

  return (
    <div className="p-8 max-w-7xl mx-auto">
      {/* Header — botón siempre visible */}
      <div className="flex flex-wrap justify-between items-start gap-4 mb-8">
        <div>
          <h1 className="text-3xl font-extrabold text-gray-800">Sedes / Instituciones</h1>
          <p className="text-gray-500">Administra las sedes e instituciones vinculadas al 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" /> Nueva Sede
        </button>
      </div>

      <DataTable
        data={colegios}
        title="Sedes e Instituciones"
        exportFilename="sedes"
        searchPlaceholder="Buscar sede..."
        searchKeys={["nombre", "ubicacion", "email"]}
        pageSize={10}
        columns={[
          { key: "nombre", label: "Sede / Logo", render: (c: any) => (
            <div className="flex items-center gap-3">
              <div className="w-11 h-11 rounded-xl flex items-center justify-center shadow-sm flex-shrink-0 overflow-hidden"
                style={{ backgroundColor: c.color || "#1e2a47" }}>
                {c.logoUrl ? <img src={c.logoUrl} alt={c.nombre} className="w-full h-full object-contain p-1" /> :
                  <span className="text-white font-extrabold text-lg">{c.nombre.charAt(0).toUpperCase()}</span>}
              </div>
              <div>
                <div className="font-bold text-gray-800 text-[15px]">{c.nombre}</div>
                <div className="text-xs text-gray-400 mt-0.5 flex items-center gap-1">
                  <span className="inline-block w-3 h-3 rounded-full border border-white shadow-sm" style={{ backgroundColor: c.color || "#1e2a47" }} />
                  {c.color || "#1e2a47"}
                </div>
              </div>
            </div>
          ), exportValue: (c: any) => c.nombre },
          { key: "email", label: "Contacto", render: (c: any) => (
            <div className="text-xs text-gray-600 space-y-1">
              {c.email && <div>{c.email}</div>}
              {c.whatsapp && <div>WA: {c.whatsapp}</div>}
              {c.telefono && <div>Tel: {c.telefono}</div>}
            </div>
          ), exportValue: (c: any) => [c.email, c.whatsapp, c.telefono].filter(Boolean).join(" | ") },
          { key: "requisitos", label: "Requisitos", render: (c: any) => (
            c.requisitosInscripcion 
            ? <span className="text-xs text-gray-600 line-clamp-2" title={c.requisitosInscripcion}>{c.requisitosInscripcion}</span> 
            : <span className="text-xs text-gray-400 italic">No definidos</span>
          ), exportValue: (c: any) => c.requisitosInscripcion || "No definidos" },
          { key: "activo", label: "Estado", render: (c: any) => (
            c.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"><CheckCircle className="w-3.5 h-3.5" /> 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"><XCircle className="w-3.5 h-3.5" /> Inactivo</span>
            )
          ), exportValue: (c: any) => c.activo ? "Activo" : "Inactivo" },
        ]}
        actions={(c: any) => (
          <div className="flex justify-end gap-2">
            <Link href={`/dashboard/instructores?colegioId=${c.id}`} className="text-purple-500 hover:bg-purple-50 p-2 rounded transition-colors" title="Ver Profesores">
              <Users className="w-4 h-4" />
            </Link>
            <Link href={`/dashboard/usuarios?colegioId=${c.id}`} className="text-indigo-500 hover:bg-indigo-50 p-2 rounded transition-colors" title="Ver Usuarios">
              <UserCircle className="w-4 h-4" />
            </Link>
            <button onClick={() => setEditingColegio(c)} 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(c.id)} disabled={loadingId === c.id}
              className="text-red-600 hover:bg-red-50 p-2 rounded transition-colors disabled:opacity-50" title="Eliminar Permanentemente">
              <Trash2 className="w-4 h-4" />
            </button>
            <button onClick={() => handleToggle(c.id, c.activo)} disabled={loadingId === c.id}
              className={`${c.activo ? 'text-amber-500 hover:bg-amber-50' : 'text-green-500 hover:bg-green-50'} p-2 rounded transition-colors disabled:opacity-50`}
              title={c.activo ? "Desactivar" : "Activar"}>
              {loadingId === c.id ? <span className="animate-spin block">⟳</span> : c.activo ? <XCircle className="w-4 h-4" /> : <CheckCircle className="w-4 h-4" />}
            </button>
          </div>
        )}
      />

      {/* Modal Crear */}
      {showCreateModal && (
        <Modal title="Agregar Nueva Sede" onClose={() => setShowCreateModal(false)}>
          <ColegioForm 
            onCancel={() => setShowCreateModal(false)} 
            onSubmit={async (fd) => {
              const res = await createColegio(fd);
              if (res.success) {
                setShowCreateModal(false);
                router.refresh();
                return { success: true };
              } else {
                return { success: false, error: res.error || "Error al crear sede" };
              }
            }}
          />
        </Modal>
      )}

      {/* Modal Editar */}
      {editingColegio && (
        <Modal title={`Editar: ${editingColegio.nombre}`} onClose={() => setEditingColegio(null)}>
          <ColegioForm 
            colegio={editingColegio} 
            onCancel={() => setEditingColegio(null)} 
            onSubmit={async (fd) => {
              const res = await updateColegio(editingColegio.id, fd);
              if (res.success) {
                setEditingColegio(null);
                router.refresh();
                return { success: true };
              } else {
                return { success: false, error: res.error || "Error al actualizar sede" };
              }
            }}
          />
        </Modal>
      )}
    </div>
  );
}

// ─── Form reutilizable con color picker ──────────────────────────────────────
function ColegioForm({ colegio, onSubmit, onCancel }: { 
  colegio?: Colegio; 
  onSubmit: (fd: FormData) => Promise<{ success: boolean; error?: string }>;
  onCancel: () => void;
}) {
  const [selectedColor, setSelectedColor] = useState(colegio?.color || "#1e2a47");
  const [logoUrl, setLogoUrl] = useState(colegio?.logoUrl || "");
  const [uploading, setUploading] = useState(false);
  const [adminPassword, setAdminPassword] = useState("");
  const [isSubmitting, setIsSubmitting] = useState(false);
  const [error, setError] = useState("");

  const generatePassword = () => {
    const chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789*";
    let pass = "";
    for (let i = 0; i < 10; i++) pass += chars.charAt(Math.floor(Math.random() * chars.length));
    setAdminPassword(pass);
  };

  const handleFileChange = async (e: React.ChangeEvent<HTMLInputElement>) => {
    const file = e.target.files?.[0];
    if (!file) return;
    setUploading(true);
    try {
      const fd = new FormData();
      fd.append("file", file);
      const res = await fetch("/api/upload", { method: "POST", body: fd });
      const data = await res.json();
      if (data.url) setLogoUrl(data.url);
      else alert(data.error || "Error al subir");
    } catch { alert("Error al subir el archivo"); }
    setUploading(false);
  };

  const handleSubmit = async (e: React.FormEvent<HTMLFormElement>) => {
    e.preventDefault();
    setError("");
    setIsSubmitting(true);
    const fd = new FormData(e.currentTarget);
    fd.set("color", selectedColor);
    fd.set("logoUrl", logoUrl);
    
    const res = await onSubmit(fd);
    if (!res.success) {
      setError(res.error || "Ocurrió un error inesperado.");
    }
    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>
      )}
      <Field label="Nombre Oficial" name="nombre" required
        defaultValue={colegio?.nombre} placeholder="Ej. Instituto Técnico Nirgua" />
      <Field label="Ubicación" name="ubicacion"
        defaultValue={colegio?.ubicacion || ""} placeholder="Av. Bolívar, Nirgua" />
      <div className="grid grid-cols-2 gap-4">
        <Field label="WhatsApp" name="whatsapp"
          defaultValue={colegio?.whatsapp || ""} placeholder="+58 414..." />
        <Field label="Email (Usado para el inicio de sesión del Admin)" name="email" type="email" required={!colegio}
          defaultValue={colegio?.email || ""} placeholder="correo@sede.com" />
      </div>
      <Field label="Teléfono" name="telefono"
        defaultValue={colegio?.telefono || ""} placeholder="0251..." />

      {/* Creación de Administrador (Solo al crear nueva sede) */}
      {!colegio && (
        <div className="bg-blue-50 p-4 rounded-xl border border-blue-100">
          <h3 className="font-bold text-blue-900 mb-1 flex items-center gap-2"><Building2 className="w-4 h-4" /> Usuario Administrador</h3>
          <p className="text-xs text-blue-700 mb-3 leading-relaxed">
            Se creará un usuario administrador automáticamente usando el <strong>Email</strong> proporcionado arriba.
          </p>
          <div>
            <label className="block text-sm font-semibold text-gray-700 mb-1">Contraseña de acceso <span className="text-red-500">*</span></label>
            <div className="flex gap-2">
              <input type="text" name="adminPassword" required value={adminPassword} onChange={e => setAdminPassword(e.target.value)}
                className="flex-1 border border-gray-200 p-3 rounded-lg focus:ring-2 focus:ring-[#0066ff] outline-none bg-white" placeholder="Escribe o genera una clave segura" />
              <button type="button" onClick={generatePassword} className="bg-[#0066ff]/10 text-[#0066ff] px-4 rounded-lg font-bold hover:bg-[#0066ff]/20 transition-colors shrink-0">
                Generar Clave
              </button>
            </div>
          </div>
        </div>
      )}

      {/* Requisitos de inscripción */}
      <div>
        <label className="block text-sm font-semibold text-gray-700 mb-1">Requisitos de Inscripción</label>
        <textarea name="requisitosInscripcion" rows={3} defaultValue={colegio?.requisitosInscripcion || ""}
          placeholder="Ej: Copia de cédula, 2 fotos tipo carnet, fondo negro del título..."
          className="w-full border border-gray-200 p-3 rounded-lg focus:ring-2 focus:ring-[#0066ff] outline-none resize-none" />
      </div>

      {/* Upload de logo */}
      <div>
        <label className="block text-sm font-semibold text-gray-700 mb-2">Logo / Imagen de la Sede</label>
        <div className="flex items-center gap-4">
          {/* Preview */}
          <div className="w-16 h-16 rounded-xl border-2 border-dashed border-gray-200 flex items-center justify-center overflow-hidden flex-shrink-0"
            style={{ backgroundColor: logoUrl ? "transparent" : selectedColor }}>
            {logoUrl ? (
              <img src={logoUrl} alt="Logo" className="w-full h-full object-contain p-1" />
            ) : (
              <span className="text-white text-2xl font-bold">{colegio?.nombre?.charAt(0) || "?"}</span>
            )}
          </div>
          <div className="flex-1">
            <label className={`flex items-center gap-2 px-4 py-2.5 rounded-lg border border-gray-200 cursor-pointer hover:bg-gray-50 transition-colors text-sm font-semibold ${uploading ? 'opacity-50 pointer-events-none' : ''}`}>
              {uploading ? (
                <><span className="animate-spin">⟳</span> Subiendo...</>
              ) : (
                <><span>📎</span> {logoUrl ? "Cambiar imagen" : "Adjuntar imagen"}</>
              )}
              <input type="file" accept="image/*" onChange={handleFileChange} className="hidden" />
            </label>
            {logoUrl && (
              <button type="button" onClick={() => setLogoUrl("")}
                className="text-xs text-red-500 hover:text-red-700 mt-1 font-semibold">
                ✕ Quitar logo
              </button>
            )}
          </div>
        </div>
      </div>

      {/* Color picker */}
      <div>
        <label className="block text-sm font-semibold text-gray-700 mb-2">
          Color institucional
        </label>
        <div className="flex flex-wrap gap-2 mb-2">
          {COLORES_PRESET.map(c => (
            <button
              key={c} type="button"
              onClick={() => setSelectedColor(c)}
              className={`w-8 h-8 rounded-lg border-2 transition-all ${selectedColor === c ? 'border-gray-800 scale-110 shadow-md' : 'border-transparent'}`}
              style={{ backgroundColor: c }}
              title={c}
            />
          ))}
        </div>
        <div className="flex items-center gap-3 mt-2">
          <input
            type="color"
            value={selectedColor}
            onChange={e => setSelectedColor(e.target.value)}
            className="w-10 h-10 rounded-lg cursor-pointer border border-gray-200 p-0.5"
          />
          <span className="text-sm text-gray-500 font-mono">{selectedColor}</span>
          <div className="w-8 h-8 rounded-lg shadow-sm border border-gray-100"
            style={{ backgroundColor: selectedColor }} />
        </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}
          {colegio ? "Guardar Cambios" : "Crear Sede"}
        </button>
      </div>
    </form>
  );

}

// ─── Helpers ─────────────────────────────────────────────────────────────────
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, placeholder, type = "text", defaultValue = "" }: {
  label: string; name: string; required?: boolean; placeholder?: string; type?: string; defaultValue?: 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>
  );
}
