'use client';

import { useEffect, useRef, useState } from 'react';
import { CrmIcon } from '@/components/crm/CrmIcon';
import { useToast } from '@/components/crm/ToastProvider';
import { searchContacts } from '@/features/inbox/api.client';
import type { SearchContact } from '@/features/inbox/types';
import { copyText } from '@/features/meetings/ui/scheduler/parts';
import { errorText } from '@/lib/api/errors';
import { cn } from '@/lib/utils/cn';
import { createDocumentShare, updateDocument, uploadDocument } from '../api.client';
import { DOCUMENT_ACCEPT, type TrackedDocument } from '../types';

/**
 * The Documents page's dialogs (HUB-419): upload, rename, move to a folder, and copy a tracked
 * link. A tracked link is made for one contact: the link records that contact's views.
 */

function DocModal({
  id,
  title,
  onClose,
  footer,
  children,
}: {
  id: string;
  title: string;
  onClose: () => void;
  footer: React.ReactNode;
  children: React.ReactNode;
}) {
  useEffect(() => {
    const onKey = (e: KeyboardEvent) => {
      if (e.key === 'Escape') onClose();
    };
    window.addEventListener('keydown', onKey);
    return () => window.removeEventListener('keydown', onKey);
  }, [onClose]);
  return (
    <div
      className="modal-backdrop is-open"
      role="presentation"
      onClick={(e) => e.target === e.currentTarget && onClose()}
    >
      <div className="modal" role="dialog" aria-modal="true" aria-labelledby={`${id}-title`}>
        <div className="modal__header">
          <h2 className="modal__title" id={`${id}-title`}>
            {title}
          </h2>
          <button type="button" className="modal__close" aria-label="Close" onClick={onClose}>
            <CrmIcon name="x" className="iconSize-20" />
          </button>
        </div>
        <div className="modal__body">{children}</div>
        <div className="modal__footer">{footer}</div>
      </div>
    </div>
  );
}

const cancelBtn = (onClose: () => void) => (
  <button type="button" className="btn-crm btn-crm--outline" onClick={onClose}>
    Cancel
  </button>
);

/** Folder names for the datalist: the ones documents are in now. */
function FolderInput({
  value,
  onChange,
  folders,
}: {
  value: string;
  onChange: (v: string) => void;
  folders: string[];
}) {
  return (
    <label className="field">
      <span className="field__label">Folder (optional)</span>
      <input
        className="input"
        list="docFolderNames"
        maxLength={100}
        placeholder="No folder"
        value={value}
        onChange={(e) => onChange(e.target.value)}
      />
      <datalist id="docFolderNames">
        {folders.map((f) => (
          <option key={f} value={f} />
        ))}
      </datalist>
    </label>
  );
}

export function UploadDialog({
  folders,
  defaultFolder,
  onClose,
  onUploaded,
}: {
  folders: string[];
  defaultFolder: string | null;
  onClose: () => void;
  onUploaded: () => void;
}) {
  const toast = useToast();
  const [file, setFile] = useState<File | null>(null);
  const [name, setName] = useState('');
  const [folder, setFolder] = useState(defaultFolder ?? '');
  const [busy, setBusy] = useState(false);
  const [error, setError] = useState<string | null>(null);
  const submit = async () => {
    if (!file || busy) return;
    setBusy(true);
    setError(null);
    try {
      await uploadDocument(file, { name: name || file.name.replace(/\.[^.]+$/, ''), folder });
      toast(`${file.name} uploaded`);
      onUploaded();
      onClose();
    } catch (err) {
      setError(errorText(err));
      setBusy(false);
    }
  };
  return (
    <DocModal
      id="docUpload"
      title="Upload document"
      onClose={onClose}
      footer={
        <>
          {cancelBtn(onClose)}
          <button
            type="button"
            className={cn('btn-crm btn-crm--primary', busy && 'is-loading')}
            disabled={!file || busy}
            onClick={() => void submit()}
          >
            Upload
          </button>
        </>
      }
    >
      <label className="field">
        <span className="field__label">File</span>
        <input
          className="input"
          type="file"
          accept={DOCUMENT_ACCEPT}
          onChange={(e) => {
            const f = e.target.files?.[0] ?? null;
            setFile(f);
            if (f && !name) setName(f.name.replace(/\.[^.]+$/, ''));
          }}
        />
        <span className="doc-muted">PDF, PowerPoint, Word or Excel, up to 25 MB.</span>
      </label>
      <label className="field">
        <span className="field__label">Name</span>
        <input
          className="input"
          maxLength={191}
          value={name}
          onChange={(e) => setName(e.target.value)}
        />
      </label>
      <FolderInput value={folder} onChange={setFolder} folders={folders} />
      {error ? (
        <p className="doc-error" role="alert">
          {error}
        </p>
      ) : null}
    </DocModal>
  );
}

export function RenameDialog({
  doc,
  onClose,
  onSaved,
}: {
  doc: TrackedDocument;
  onClose: () => void;
  onSaved: () => void;
}) {
  const toast = useToast();
  const [name, setName] = useState(doc.name);
  const [busy, setBusy] = useState(false);
  const save = async () => {
    if (!name.trim() || busy) return;
    setBusy(true);
    try {
      await updateDocument(doc.id, { name: name.trim() });
      toast('Document renamed');
      onSaved();
      onClose();
    } catch (err) {
      toast(errorText(err), 'danger');
      setBusy(false);
    }
  };
  return (
    <DocModal
      id="docRename"
      title="Rename document"
      onClose={onClose}
      footer={
        <>
          {cancelBtn(onClose)}
          <button
            type="button"
            className="btn-crm btn-crm--primary"
            disabled={!name.trim() || busy}
            onClick={() => void save()}
          >
            Save
          </button>
        </>
      }
    >
      <label className="field">
        <span className="field__label">Name</span>
        <input
          className="input"
          maxLength={191}
          autoFocus
          value={name}
          onChange={(e) => setName(e.target.value)}
          onKeyDown={(e) => e.key === 'Enter' && void save()}
        />
      </label>
    </DocModal>
  );
}

export function MoveDialog({
  doc,
  folders,
  onClose,
  onSaved,
}: {
  doc: TrackedDocument;
  folders: string[];
  onClose: () => void;
  onSaved: () => void;
}) {
  const toast = useToast();
  const [folder, setFolder] = useState(doc.folder ?? '');
  const [busy, setBusy] = useState(false);
  const save = async () => {
    if (busy) return;
    setBusy(true);
    try {
      await updateDocument(doc.id, { folder: folder.trim() || null });
      toast(folder.trim() ? `Moved to ${folder.trim()}` : 'Moved out of its folder');
      onSaved();
      onClose();
    } catch (err) {
      toast(errorText(err), 'danger');
      setBusy(false);
    }
  };
  return (
    <DocModal
      id="docMove"
      title="Move document"
      onClose={onClose}
      footer={
        <>
          {cancelBtn(onClose)}
          <button
            type="button"
            className="btn-crm btn-crm--primary"
            disabled={busy}
            onClick={() => void save()}
          >
            Move
          </button>
        </>
      }
    >
      <FolderInput value={folder} onChange={setFolder} folders={folders} />
      <p className="doc-muted">Leave it empty to take the document out of its folder.</p>
    </DocModal>
  );
}

export function LinkDialog({ doc, onClose }: { doc: TrackedDocument; onClose: () => void }) {
  const toast = useToast();
  const [q, setQ] = useState('');
  const [found, setFound] = useState<SearchContact[]>([]);
  const [searching, setSearching] = useState(false);
  const [url, setUrl] = useState<string | null>(null);
  const [forName, setForName] = useState('');
  const [error, setError] = useState<string | null>(null);
  const request = useRef(0);

  useEffect(() => {
    const term = q.trim();
    if (term.length < 2) {
      setFound([]);
      return;
    }
    const id = ++request.current;
    setSearching(true);
    const t = window.setTimeout(() => {
      searchContacts(term).then(
        (res) => {
          if (id !== request.current) return;
          setFound(res.contacts);
          setSearching(false);
        },
        () => id === request.current && setSearching(false),
      );
    }, 250);
    return () => window.clearTimeout(t);
  }, [q]);

  const pick = async (c: SearchContact) => {
    setError(null);
    try {
      const share = await createDocumentShare(doc.id, c.id);
      setUrl(share.url);
      setForName(c.displayName);
      if (await copyText(share.url)) toast('Tracked link copied');
    } catch (err) {
      setError(errorText(err));
    }
  };

  return (
    <DocModal
      id="docLink"
      title={`Copy tracked link: ${doc.name}`}
      onClose={onClose}
      footer={
        <button type="button" className="btn-crm btn-crm--outline" onClick={onClose}>
          Close
        </button>
      }
    >
      {url ? (
        <>
          <p className="doc-muted">
            Link for <strong>{forName}</strong>. Their views of the document are recorded.
          </p>
          <div className="doc-link-row">
            <input className="input" readOnly value={url} onFocus={(e) => e.target.select()} />
            <button
              type="button"
              className="btn-crm btn-crm--primary btn-crm--sm"
              onClick={async () =>
                toast((await copyText(url)) ? 'Tracked link copied' : 'Copy it by hand', 'info')
              }
            >
              Copy
            </button>
          </div>
        </>
      ) : (
        <>
          <label className="field">
            <span className="field__label">Who is it for?</span>
            <input
              className="input"
              autoFocus
              placeholder="Search contacts by name or email"
              value={q}
              onChange={(e) => setQ(e.target.value)}
            />
          </label>
          <p className="doc-muted">
            A tracked link is made for one contact, so their views are recorded on them.
          </p>
          {searching ? <p className="doc-muted">Searching…</p> : null}
          <ul className="doc-results">
            {found.map((c) => (
              <li key={c.id}>
                <button type="button" onClick={() => void pick(c)}>
                  <strong>{c.displayName}</strong>
                  <span className="doc-muted">
                    {[c.email, c.companyName].filter(Boolean).join(' · ')}
                  </span>
                </button>
              </li>
            ))}
          </ul>
          {error ? (
            <p className="doc-error" role="alert">
              {error}
            </p>
          ) : null}
        </>
      )}
    </DocModal>
  );
}
