"use client";

import { useState, useEffect, useCallback } from "react";
import type { UserPublic, UserRole } from "@/src/types/user";
import { ROLE_LABELS, USER_ROLES } from "@/src/lib/permissions";

function FormModal({
  title,
  onClose,
  onSubmit,
  children,
  submitLabel,
}: {
  title: string;
  onClose: () => void;
  onSubmit: (e: React.FormEvent) => void;
  children: React.ReactNode;
  submitLabel: string;
}) {
  return (
    <div className="fixed inset-0 z-50 flex items-center justify-center p-4">
      <div className="absolute inset-0 bg-black/70 backdrop-blur-sm" onClick={onClose} />
      <div className="relative w-full max-w-md rounded-xl bg-zinc-900 border border-zinc-700 p-6 shadow-xl">
        <h3 className="text-lg font-semibold text-white mb-4">{title}</h3>
        <form onSubmit={onSubmit} className="space-y-4">
          {children}
          <div className="flex justify-end gap-3 pt-2">
            <button
              type="button"
              onClick={onClose}
              className="px-4 py-2 rounded-lg border border-zinc-700 text-zinc-300 hover:bg-zinc-800"
            >
              Annulla
            </button>
            <button
              type="submit"
              className="px-4 py-2 rounded-lg bg-blue-600 text-white hover:bg-blue-500"
            >
              {submitLabel}
            </button>
          </div>
        </form>
      </div>
    </div>
  );
}

function formatLastLogin(value?: Date | string | null): string {
  if (!value) return "Mai";
  const d = value instanceof Date ? value : new Date(value);
  if (Number.isNaN(d.getTime())) return "—";
  return d.toLocaleString("it-IT", {
    day: "2-digit",
    month: "2-digit",
    year: "numeric",
    hour: "2-digit",
    minute: "2-digit",
  });
}

function roleBadgeClass(ruolo: UserRole): string {
  switch (ruolo) {
    case "amministratore":
      return "bg-purple-900/40 text-purple-300 border-purple-800";
    case "tecnico":
      return "bg-blue-900/40 text-blue-300 border-blue-800";
    case "operatore":
      return "bg-zinc-800 text-zinc-300 border-zinc-700";
  }
}

export default function UtentiManager() {
  const [utenti, setUtenti] = useState<UserPublic[]>([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);
  const [search, setSearch] = useState("");
  const [modal, setModal] = useState<"create" | "edit" | null>(null);
  const [editing, setEditing] = useState<UserPublic | null>(null);

  const [formUtente, setFormUtente] = useState("");
  const [formMail, setFormMail] = useState("");
  const [formRuolo, setFormRuolo] = useState<UserRole>("operatore");
  const [formAttivo, setFormAttivo] = useState<0 | 1>(1);
  const [formPassword, setFormPassword] = useState("");

  const loadData = useCallback(async () => {
    setLoading(true);
    setError(null);
    try {
      const res = await fetch("/api/utenti");
      if (!res.ok) {
        const data = await res.json();
        throw new Error(data.error || "Errore nel caricamento");
      }
      const data = await res.json();
      setUtenti(data.utenti || []);
    } catch (err) {
      setError(err instanceof Error ? err.message : "Errore sconosciuto");
    } finally {
      setLoading(false);
    }
  }, []);

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

  const resetForm = () => {
    setFormUtente("");
    setFormMail("");
    setFormRuolo("operatore");
    setFormAttivo(1);
    setFormPassword("");
  };

  const openCreate = () => {
    setEditing(null);
    resetForm();
    setModal("create");
  };

  const openEdit = (user: UserPublic) => {
    setEditing(user);
    setFormUtente(user.utente);
    setFormMail(user.mail);
    setFormRuolo(user.ruolo);
    setFormAttivo(user.attivo);
    setFormPassword("");
    setModal("edit");
  };

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    setError(null);
    try {
      const url = modal === "edit" && editing ? `/api/utenti/${editing.id}` : "/api/utenti";
      const method = modal === "edit" ? "PUT" : "POST";
      const body: Record<string, unknown> = {
        utente: formUtente,
        mail: formMail,
        ruolo: formRuolo,
        attivo: formAttivo,
      };
      if (formPassword) {
        body.password = formPassword;
      }

      const res = await fetch(url, {
        method,
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify(body),
      });
      const data = await res.json();
      if (!res.ok) throw new Error(data.error || "Operazione fallita");
      setModal(null);
      await loadData();
    } catch (err) {
      setError(err instanceof Error ? err.message : "Errore");
    }
  };

  const handleDelete = async (user: UserPublic) => {
    if (!confirm(`Eliminare l'utente "${user.utente}"?`)) return;
    setError(null);
    try {
      const res = await fetch(`/api/utenti/${user.id}`, { method: "DELETE" });
      const data = await res.json();
      if (!res.ok) throw new Error(data.error || "Eliminazione fallita");
      await loadData();
    } catch (err) {
      setError(err instanceof Error ? err.message : "Errore");
    }
  };

  const filtered = utenti.filter(
    (u) =>
      u.utente.toLowerCase().includes(search.toLowerCase()) ||
      u.mail.toLowerCase().includes(search.toLowerCase()) ||
      ROLE_LABELS[u.ruolo].toLowerCase().includes(search.toLowerCase()),
  );

  const attivi = utenti.filter((u) => u.attivo === 1).length;

  return (
    <div>
      <div className="mb-6">
        <h1 className="text-2xl font-bold text-white">Gestione utenti</h1>
        <p className="text-sm text-zinc-500">
          Amministratori, tecnici e operatori con permessi differenziati
        </p>
      </div>

      <div className="grid grid-cols-2 gap-4 mb-6">
        <div className="p-4 rounded-xl bg-zinc-900 border border-zinc-800">
          <p className="text-sm text-zinc-500">Utenti totali</p>
          <p className="text-2xl font-bold text-white">{utenti.length}</p>
        </div>
        <div className="p-4 rounded-xl bg-zinc-900 border border-zinc-800">
          <p className="text-sm text-zinc-500">Attivi</p>
          <p className="text-2xl font-bold text-green-400">{attivi}</p>
        </div>
      </div>

      {error && (
        <div className="mb-4 p-4 rounded-lg bg-red-500/10 border border-red-500/30 text-red-400 text-sm flex justify-between items-center">
          <span>{error}</span>
          <button type="button" onClick={() => setError(null)} className="text-red-300 hover:text-white">
            ✕
          </button>
        </div>
      )}

      <div className="flex flex-col md:flex-row gap-4 items-start md:items-center justify-between mb-6">
        <input
          type="text"
          value={search}
          onChange={(e) => setSearch(e.target.value)}
          placeholder="Cerca per nome, email o ruolo..."
          className="w-full md:max-w-md px-4 py-2 rounded-lg bg-zinc-900 border border-zinc-800 text-white placeholder-zinc-500 focus:outline-none focus:border-blue-500"
        />
        <button
          type="button"
          onClick={openCreate}
          className="px-4 py-2 rounded-lg bg-blue-600 text-white font-medium hover:bg-blue-500"
        >
          Nuovo utente
        </button>
      </div>

      {loading ? (
        <div className="flex items-center justify-center py-20 text-zinc-500">
          <svg className="w-6 h-6 animate-spin mr-3" viewBox="0 0 24 24">
            <circle className="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" strokeWidth="4" fill="none" />
            <path className="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4z" />
          </svg>
          Caricamento...
        </div>
      ) : filtered.length === 0 ? (
        <div className="p-12 rounded-xl bg-zinc-900 border border-zinc-800 text-center">
          <h3 className="text-lg font-medium text-white mb-2">Nessun utente</h3>
          <p className="text-zinc-500 mb-4">
            {search ? "Nessun risultato per la ricerca" : "Aggiungi il primo utente"}
          </p>
          {!search && (
            <button
              type="button"
              onClick={openCreate}
              className="px-4 py-2 rounded-lg bg-blue-600 text-white hover:bg-blue-500"
            >
              Crea utente
            </button>
          )}
        </div>
      ) : (
        <div className="rounded-xl bg-zinc-900 border border-zinc-800 overflow-hidden">
          <table className="w-full text-sm">
            <thead>
              <tr className="border-b border-zinc-800 text-zinc-500 text-left">
                <th className="px-4 py-3 font-medium">Utente</th>
                <th className="px-4 py-3 font-medium">Email</th>
                <th className="px-4 py-3 font-medium">Ruolo</th>
                <th className="px-4 py-3 font-medium">Stato</th>
                <th className="px-4 py-3 font-medium">Ultimo accesso</th>
                <th className="px-4 py-3 font-medium text-right">Azioni</th>
              </tr>
            </thead>
            <tbody>
              {filtered.map((user) => (
                <tr key={user.id} className="border-b border-zinc-800/80 hover:bg-zinc-800/30">
                  <td className="px-4 py-3 text-white font-medium">{user.utente}</td>
                  <td className="px-4 py-3 text-zinc-400">{user.mail}</td>
                  <td className="px-4 py-3">
                    <span
                      className={`inline-block px-2 py-0.5 rounded text-xs border ${roleBadgeClass(user.ruolo)}`}
                    >
                      {ROLE_LABELS[user.ruolo]}
                    </span>
                  </td>
                  <td className="px-4 py-3">
                    {user.attivo === 1 ? (
                      <span className="text-green-400">Attivo</span>
                    ) : (
                      <span className="text-zinc-500">Disattivo</span>
                    )}
                  </td>
                  <td className="px-4 py-3 text-zinc-500 text-xs">
                    {formatLastLogin(user.last_login)}
                  </td>
                  <td className="px-4 py-3">
                    <div className="flex justify-end gap-1">
                      <button
                        type="button"
                        onClick={() => openEdit(user)}
                        className="p-2 rounded-lg text-zinc-400 hover:text-white hover:bg-zinc-800"
                        title="Modifica"
                      >
                        <svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                          <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M11 5H6a2 2 0 00-2 2v11a2 2 0 002 2h11a2 2 0 002-2v-5m-1.414-9.414a2 2 0 112.828 2.828L11.828 15H9v-2.828l8.586-8.586z" />
                        </svg>
                      </button>
                      <button
                        type="button"
                        onClick={() => handleDelete(user)}
                        className="p-2 rounded-lg text-red-400 hover:text-red-300 hover:bg-red-500/10"
                        title="Elimina"
                      >
                        <svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                          <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M19 7l-.867 12.142A2 2 0 0116.138 21H7.862a2 2 0 01-1.995-1.858L5 7m5 4v6m4-6v6m1-10V4a1 1 0 00-1-1h-4a1 1 0 00-1 1v3M4 7h16" />
                        </svg>
                      </button>
                    </div>
                  </td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
      )}

      {modal && (
        <FormModal
          title={modal === "edit" ? "Modifica utente" : "Nuovo utente"}
          onClose={() => setModal(null)}
          onSubmit={handleSubmit}
          submitLabel={modal === "edit" ? "Salva" : "Crea"}
        >
          <div>
            <label className="block text-xs text-zinc-400 mb-1">Nome utente</label>
            <input
              type="text"
              value={formUtente}
              onChange={(e) => setFormUtente(e.target.value)}
              required
              className="w-full px-3 py-2 rounded-lg bg-zinc-950 border border-zinc-700 text-white focus:outline-none focus:border-blue-500"
            />
          </div>
          <div>
            <label className="block text-xs text-zinc-400 mb-1">Email</label>
            <input
              type="email"
              value={formMail}
              onChange={(e) => setFormMail(e.target.value)}
              required
              className="w-full px-3 py-2 rounded-lg bg-zinc-950 border border-zinc-700 text-white focus:outline-none focus:border-blue-500"
            />
          </div>
          <div>
            <label className="block text-xs text-zinc-400 mb-1">Ruolo</label>
            <select
              value={formRuolo}
              onChange={(e) => setFormRuolo(e.target.value as UserRole)}
              className="w-full px-3 py-2 rounded-lg bg-zinc-950 border border-zinc-700 text-white focus:outline-none focus:border-blue-500"
            >
              {USER_ROLES.map((r) => (
                <option key={r} value={r}>
                  {ROLE_LABELS[r]}
                </option>
              ))}
            </select>
          </div>
          <div>
            <label className="block text-xs text-zinc-400 mb-1">Stato</label>
            <select
              value={formAttivo}
              onChange={(e) => setFormAttivo(parseInt(e.target.value, 10) as 0 | 1)}
              className="w-full px-3 py-2 rounded-lg bg-zinc-950 border border-zinc-700 text-white focus:outline-none focus:border-blue-500"
            >
              <option value={1}>Attivo</option>
              <option value={0}>Disattivo</option>
            </select>
          </div>
          <div>
            <label className="block text-xs text-zinc-400 mb-1">
              Password {modal === "edit" && "(lascia vuoto per non cambiare)"}
            </label>
            <input
              type="password"
              value={formPassword}
              onChange={(e) => setFormPassword(e.target.value)}
              required={modal === "create"}
              minLength={6}
              className="w-full px-3 py-2 rounded-lg bg-zinc-950 border border-zinc-700 text-white focus:outline-none focus:border-blue-500"
            />
          </div>
        </FormModal>
      )}
    </div>
  );
}
