'use client';

import { useRef, useState } from 'react';
import { AnchoredPopover } from '@/components/crm/AnchoredPopover';
import { useToast } from '@/components/crm/ToastProvider';
import { errorText } from '@/lib/api/errors';
import { createDocumentPreviewLink, fetchDocumentFile } from '../api.client';
import type { TrackedDocument } from '../types';

/**
 * The row's hover tools from the 17 Nov design (documents.php): Preview opens the public
 * `/d/p/...` viewer; Actions lists Copy tracked link, Rename, Download, Delete and Move.
 */
export function DocumentRowActions({
  doc,
  onLink,
  onRename,
  onMove,
  onDelete,
}: {
  doc: TrackedDocument;
  onLink: () => void;
  onRename: () => void;
  onMove: () => void;
  onDelete: () => void;
}) {
  const toast = useToast();
  const ref = useRef<HTMLButtonElement>(null);
  const [open, setOpen] = useState(false);
  const [busy, setBusy] = useState(false);

  const withFile = async (handle: (url: string) => void, onError?: () => void) => {
    if (busy) return;
    setBusy(true);
    try {
      const blob = await fetchDocumentFile(doc.id);
      const url = URL.createObjectURL(new Blob([blob], { type: doc.mimeType }));
      handle(url);
      window.setTimeout(() => URL.revokeObjectURL(url), 60_000);
    } catch (err) {
      onError?.();
      toast(`The file could not be opened: ${errorText(err)}`, 'danger');
    } finally {
      setBusy(false);
    }
  };

  const preview = async () => {
    if (busy) return;
    setBusy(true);
    try {
      const link = await createDocumentPreviewLink(doc.id, {
        allowDownload: doc.allowDownload,
        requireEmail: false,
      });
      window.open(link.path, '_blank', 'noopener,noreferrer');
    } catch (err) {
      toast(`Could not open preview: ${errorText(err)}`, 'danger');
    } finally {
      setBusy(false);
    }
  };

  const download = () =>
    withFile((url) => {
      const a = document.createElement('a');
      a.href = url;
      a.download = doc.filename;
      document.body.appendChild(a);
      a.click();
      a.remove();
    });

  const item = (label: string, run: () => void) => (
    <button
      type="button"
      role="menuitem"
      className="doc-menu__item"
      onClick={() => {
        setOpen(false);
        run();
      }}
    >
      {label}
    </button>
  );

  return (
    <span className="doc-row-tools">
      <button
        type="button"
        className="btn-crm btn-crm--outline btn-crm--sm"
        disabled={busy}
        onClick={() => void preview()}
      >
        Preview <span aria-hidden="true">↗</span>
      </button>
      <button
        ref={ref}
        type="button"
        className="btn-crm btn-crm--outline btn-crm--sm"
        aria-haspopup="menu"
        aria-expanded={open}
        onClick={() => setOpen((v) => !v)}
      >
        Actions <span aria-hidden="true">▾</span>
      </button>
      <AnchoredPopover
        open={open}
        anchorRef={ref}
        onClose={() => setOpen(false)}
        className="doc-menu"
        align="end"
        fitContent
        menu
        label={`Actions for ${doc.name}`}
      >
        <div role="menu">
          {item('Copy tracked link', onLink)}
          {item('Rename', onRename)}
          {item('Download', () => void download())}
          {item('Delete', onDelete)}
          {item('Move', onMove)}
        </div>
      </AnchoredPopover>
    </span>
  );
}
