"use client";

import { useState } from "react";
import { addShare, removeShare } from "@/actions/share";

interface User {
  id: string;
  email: string;
  name: string | null;
}

interface SharedUser {
  id: string;
  user: { id: string; email: string; name: string | null };
}

interface ShareModalProps {
  isOpen: boolean;
  onClose: () => void;
  evaluationId: string;
  evaluatorId?: string | null;
  users: User[];
  sharedWith: SharedUser[];
  onUpdate: () => void;
}

export function ShareModal({
  isOpen,
  onClose,
  evaluationId,
  evaluatorId,
  users,
  sharedWith,
  onUpdate,
}: ShareModalProps) {
  const [shareUserId, setShareUserId] = useState("");
  const [loading, setLoading] = useState(false);

  if (!isOpen) return null;

  const availableUsers = users.filter(
    (u) => u.id !== evaluatorId && !sharedWith.some((s) => s.user.id === u.id)
  );

  async function handleAdd() {
    if (!shareUserId) return;
    setLoading(true);
    try {
      const result = await addShare(evaluationId, shareUserId);
      if (result.success) {
        setShareUserId("");
        onUpdate();
      } else {
        alert(result.error);
      }
    } finally {
      setLoading(false);
    }
  }

  async function handleRemove(userId: string) {
    const result = await removeShare(evaluationId, userId);
    if (result.success) onUpdate();
  }

  return (
    <>
      <div className="fixed inset-0 z-40 bg-black/60" onClick={onClose} aria-hidden="true" />
      <div
        className="fixed left-1/2 top-1/2 z-50 w-[calc(100%-2rem)] max-w-sm -translate-x-1/2 -translate-y-1/2 rounded-lg border border-zinc-200 dark:border-zinc-600 bg-white dark:bg-zinc-800 p-4 shadow-xl"
        role="dialog"
        aria-label="Partager"
      >
        <h3 className="mb-4 font-mono text-sm font-medium text-zinc-800 dark:text-zinc-200">
          Partager
        </h3>
        <p className="mb-3 font-mono text-xs text-zinc-600 dark:text-zinc-400">
          Ajouter un utilisateur pour lui donner accès.
        </p>
        <div className="mb-3 flex flex-col gap-2 sm:flex-row sm:items-center">
          <select
            value={shareUserId}
            onChange={(e) => setShareUserId(e.target.value)}
            className="w-full min-w-0 rounded border border-zinc-300 dark:border-zinc-600 bg-white dark:bg-zinc-700/80 px-2.5 py-1.5 text-sm text-zinc-900 dark:text-zinc-100 sm:flex-1"
          >
            <option value="">— choisir —</option>
            {availableUsers.map((u) => (
              <option key={u.id} value={u.id}>
                {u.name || u.email} ({u.email})
              </option>
            ))}
          </select>
          <button
            type="button"
            disabled={!shareUserId || loading}
            onClick={handleAdd}
            className="w-full shrink-0 rounded border border-cyan-500/50 bg-cyan-500/10 px-3 py-1.5 font-mono text-xs text-cyan-600 dark:text-cyan-400 hover:bg-cyan-500/20 disabled:opacity-50 sm:w-auto"
          >
            {loading ? "..." : "ajouter"}
          </button>
        </div>
        {sharedWith.length > 0 && (
          <ul className="mb-4 space-y-1 font-mono text-xs text-zinc-600 dark:text-zinc-400">
            {sharedWith.map((s) => (
              <li key={s.id} className="flex items-center justify-between gap-2">
                <span>{s.user.name || s.user.email}</span>
                <button
                  type="button"
                  onClick={() => handleRemove(s.user.id)}
                  className="text-red-500 hover:text-red-400"
                  title="Retirer"
                >
                  ×
                </button>
              </li>
            ))}
          </ul>
        )}
        <button
          type="button"
          onClick={onClose}
          className="w-full rounded border border-zinc-300 dark:border-zinc-700 py-2 font-mono text-xs text-zinc-600 dark:text-zinc-500 hover:bg-zinc-100 dark:hover:bg-zinc-800"
        >
          fermer
        </button>
      </div>
    </>
  );
}
