import { useState } from "react";
import { Icon } from "../../../components/Icon.jsx";

export function LinksModule({ toolboxId, moduleId, context, editing }) {
  const data = context.normalizeLinksData(context.getModuleData(toolboxId, moduleId, { links: [] }));
  const [title, setTitle] = useState("");
  const [url, setUrl] = useState("");
  const [copiedId, setCopiedId] = useState("");

  function save(links) {
    context.setModuleData(toolboxId, moduleId, { links });
  }

  function addLink(event) {
    event.preventDefault();
    const cleanUrl = context.normalizeUrl(url);
    if (!cleanUrl) return;

    save([
      ...data.links,
      {
        id: context.uid("link"),
        title: title.trim(),
        url: cleanUrl
      }
    ]);
    setTitle("");
    setUrl("");
  }

  async function copyUrl(link) {
    const copied = await context.copyText(link.url);
    if (!copied) return;
    setCopiedId(link.id);
    window.setTimeout(() => setCopiedId(""), 1400);
  }

  return (
    <>
      {editing && (
        <form className="inline-form links-add-form module-add-panel" onSubmit={addLink}>
          <input name="title" placeholder="Nom du lien" value={title} onChange={(event) => setTitle(event.target.value)} />
          <input name="url" placeholder="https://..." value={url} onChange={(event) => setUrl(event.target.value)} />
          <button className="primary">Ajouter</button>
        </form>
      )}
      <ul className="links-list">
        {data.links.map((link) => (
          <li className="link-item" key={link.id}>
            <a href={link.url} target="_blank" rel="noreferrer" title={link.url}>
              <strong>{link.title || context.hostnameFromUrl(link.url)}</strong>
              <span>{link.url}</span>
            </a>
            <div>
              <button type="button" onClick={() => copyUrl(link)} aria-label={`Copier ${link.title || link.url}`} title={copiedId === link.id ? "Copié" : "Copier"}>
                <Icon name="copy" />
              </button>
              <button type="button" className="danger" onClick={() => save(data.links.filter((item) => item.id !== link.id))} aria-label={`Supprimer ${link.title || link.url}`} title="Supprimer">
                <Icon name="trash" />
              </button>
            </div>
          </li>
        ))}
      </ul>
    </>
  );
}
