'use client';

import { useEffect, useRef, useState } from 'react';
import { useToast } from '@/components/crm/ToastProvider';
import { CollapsibleCard, usePreviewSectionLook } from '@/features/contacts/ui/CollapsibleCard';
import { CompanyCard, CompanyCardTitle } from '@/features/contacts/ui/CollapsibleCard';
import { Icon } from '@/features/objects/ui/icons';
import { errorText } from '@/lib/api/errors';
import {
  fileDownloadUrl,
  listRecordFiles,
  MAX_FILE_BYTES,
  unlinkFile,
  uploadRecordFile,
  type CrmFile,
  type FileLink,
} from '../api.client';

const EMPTY = 'See the files attached to your activities or uploaded to this record.';

const size = (bytes: number) =>
  bytes / 1024 < 1024
    ? `${Math.max(1, Math.round(bytes / 1024))} KB`
    : `${(bytes / 1048576).toFixed(1)} MB`;

const when = (iso: string) =>
  new Date(iso).toLocaleDateString(undefined, { day: 'numeric', month: 'short', year: 'numeric' });

/** The record's files: load, upload (25 MB each), download and take off the record. */
/** `refreshKey`: loads again when it changes (a note with attachments was just logged). */
function useAttachments(link: FileLink, refreshKey = 0) {
  const toast = useToast();
  const [files, setFiles] = useState<CrmFile[] | null>(null);
  const [error, setError] = useState<string | null>(null);
  const [uploading, setUploading] = useState(false);

  useEffect(() => {
    let live = true;
    // The record's own files and those on its notes and emails, which show on every record
    // the note is on (HUB-325).
    listRecordFiles(link, { includeActivities: true }).then(
      (list) => {
        if (live) setFiles(list);
      },
      (err: unknown) => {
        if (live) setError(errorText(err));
      },
    );
    return () => {
      live = false;
    };
  }, [link.type, link.id, refreshKey]); // eslint-disable-line react-hooks/exhaustive-deps

  const upload = async (picked: File[]) => {
    const big = picked.filter((f) => f.size > MAX_FILE_BYTES);
    if (big.length) {
      toast(
        `${big.length} file${big.length === 1 ? ' is' : 's are'} over 25 MB and ${big.length === 1 ? 'was' : 'were'} skipped`,
        'danger',
      );
    }
    const ok = picked.filter((f) => f.size <= MAX_FILE_BYTES);
    if (!ok.length) return;
    setUploading(true);
    let done = 0;
    for (const file of ok) {
      try {
        const saved = await uploadRecordFile(link, file);
        setFiles((cur) => [saved, ...(cur ?? [])]);
        done++;
      } catch (err) {
        toast(`${file.name}: ${errorText(err)}`, 'danger');
      }
    }
    setUploading(false);
    if (done) toast(`${done} file${done === 1 ? '' : 's'} attached`, 'success');
  };

  const download = async (file: CrmFile) => {
    try {
      window.location.assign(await fileDownloadUrl(file.id));
    } catch (err) {
      toast(errorText(err), 'danger');
    }
  };

  const remove = async (file: CrmFile) => {
    try {
      await unlinkFile(file.id, link);
      setFiles((cur) => (cur ?? []).filter((f) => f.id !== file.id));
      toast('Attachment removed', 'success');
    } catch (err) {
      toast(errorText(err), 'danger');
    }
  };

  /** On this record itself (not only through one of its activities): it can be removed here. */
  const isOwn = (file: CrmFile) => file.links.some((l) => l.type === link.type && l.id === link.id);

  return { files, error, uploading, upload, download, remove, isOwn };
}

function FileList({
  state,
  canEdit,
}: {
  state: ReturnType<typeof useAttachments>;
  canEdit: boolean;
}) {
  const { files, error } = state;
  if (error) return <p className="evr-side__empty">{error}</p>;
  if (files === null) return <p className="evr-side__empty">Loading…</p>;
  if (!files.length) return <p className="evr-side__empty">{EMPTY}</p>;
  return (
    <ul className="evr-files">
      {files.map((f) => (
        <li key={f.id}>
          <span className="evr-files__ico" aria-hidden>
            <Icon name="file" size={16} />
          </span>
          <div>
            <button
              type="button"
              className="evr-files__name"
              title={`Download ${f.name}`}
              onClick={() => void state.download(f)}
            >
              {f.name}
            </button>
            <small>
              {size(f.sizeBytes)} · {when(f.createdAt)}
              {state.isOwn(f) ? '' : ' · On an activity'}
            </small>
          </div>
          {canEdit && state.isOwn(f) ? (
            <button
              type="button"
              className="ev-iconbtn ev-iconbtn--xs"
              aria-label={`Remove ${f.name}`}
              title="Remove"
              onClick={() => void state.remove(f)}
            >
              <Icon name="x" size={12} />
            </button>
          ) : null}
        </li>
      ))}
    </ul>
  );
}

function FilePicker({
  inputRef,
  onPick,
}: {
  inputRef: React.RefObject<HTMLInputElement | null>;
  onPick: (files: File[]) => void;
}) {
  return (
    <input
      ref={inputRef}
      type="file"
      className="crm-visually-hidden"
      multiple
      tabIndex={-1}
      aria-hidden
      onChange={(e) => {
        onPick(Array.from(e.target.files ?? []));
        e.target.value = '';
      }}
    />
  );
}

/**
 * Attachments (HUB-325; design: event-details.php) on a custom-object record's right column:
 * the files uploaded to the record (GET/POST /files), downloaded through a signed URL and
 * removed from the record (the file stays on its other records).
 */
export function RecordAttachmentsCard({
  link,
  canEdit,
  onCustomize,
  refreshKey,
  designAdd = false,
}: {
  link: FileLink;
  canEdit: boolean;
  /** The gear; none on events, whose design card has none (record-tabs.js:318-321, EV18a). */
  onCustomize?: () => void;
  /** Bumped when an activity is logged on the record: its attachments may show here. */
  refreshKey?: number;
  /**
   * EV11 (event record page): the design's "Add ▾" menu (record-tabs.js:318-321), as on the
   * contact and company pages (R6b). Off: "+ Add" uploads at once (master).
   */
  designAdd?: boolean;
}) {
  const state = useAttachments(link, refreshKey);
  const input = useRef<HTMLInputElement>(null);
  const [open, setOpen] = useState(true);
  return (
    <section className="evr-side">
      <header className="evr-side__head">
        <button
          type="button"
          className="evr-card__toggle"
          aria-expanded={open}
          onClick={() => setOpen((v) => !v)}
        >
          <Icon name={open ? 'chevronDown' : 'chevronRight'} size={12} />
          <span>Attachments ({state.files?.length ?? 0})</span>
        </button>
        {canEdit && designAdd ? (
          <AttachAddMenu
            className="evr-link-btn"
            uploading={state.uploading}
            onComputer={() => input.current?.click()}
          />
        ) : canEdit ? (
          <button
            type="button"
            className="evr-link-btn"
            disabled={state.uploading}
            onClick={() => input.current?.click()}
          >
            <Icon name="plus" size={10} /> {state.uploading ? 'Uploading…' : 'Add'}
          </button>
        ) : null}
        {onCustomize ? (
          <button
            type="button"
            className="ev-iconbtn ev-iconbtn--xs"
            aria-label="Customize the Attachments card"
            title="Customize"
            onClick={onCustomize}
          >
            <Icon name="gear" size={12} />
          </button>
        ) : null}
      </header>
      {open ? <FileList state={state} canEdit={canEdit} /> : null}
      <FilePicker inputRef={input} onPick={(files) => void state.upload(files)} />
    </section>
  );
}

/** Attachments (HUB-325) on the contact, company and deal pages' right column. */
export function AttachmentsSidebarCard({
  link,
  canEdit,
  variant = 'contact',
  refreshKey,
  designAdd = false,
}: {
  link: FileLink;
  canEdit: boolean;
  /** `company`: the company page's card style (company-details.css). */
  variant?: 'contact' | 'company';
  /** Changes after an activity is logged, to show its attachments. */
  refreshKey?: number;
  /**
   * R6b (contact and company record pages): the design's "Add ▾" menu (record-tabs.js:318-321)
   * with "Your computer" and "Existing file in CRM". Off: "+ Add" uploads at once, as before.
   */
  designAdd?: boolean;
}) {
  const state = useAttachments(link, refreshKey);
  const input = useRef<HTMLInputElement>(null);
  // B4: in Companies' list preview the card is the design's section, and + Add its link button.
  const inPreview = usePreviewSectionLook();
  if (variant === 'company') {
    return (
      <CompanyCard cardId="attachments">
        <div className="company-card-head">
          <CompanyCardTitle>Attachments ({state.files?.length ?? 0})</CompanyCardTitle>
          {canEdit && designAdd ? (
            <AttachAddMenu
              className="company-add-link"
              uploading={state.uploading}
              onComputer={() => input.current?.click()}
            />
          ) : canEdit ? (
            <button
              type="button"
              className="company-add-link"
              aria-label="Attach files"
              disabled={state.uploading}
              onClick={() => input.current?.click()}
            >
              {state.uploading ? 'Uploading…' : '+ Add'}
            </button>
          ) : null}
        </div>
        <FileList state={state} canEdit={canEdit} />
        <FilePicker inputRef={input} onPick={(files) => void state.upload(files)} />
      </CompanyCard>
    );
  }
  return (
    <CollapsibleCard
      title={`Attachments (${state.files?.length ?? 0})`}
      cardId="attachments"
      action={
        canEdit && designAdd && !inPreview ? (
          <AttachAddMenu
            className="crm-collapsible-card__action"
            uploading={state.uploading}
            onComputer={() => input.current?.click()}
          />
        ) : canEdit ? (
          <button
            type="button"
            className={inPreview ? 'lp-link' : 'crm-collapsible-card__action'}
            aria-label="Attach files"
            disabled={state.uploading}
            onClick={() => input.current?.click()}
          >
            {state.uploading ? 'Uploading…' : '+ Add'}
          </button>
        ) : undefined
      }
    >
      <FileList state={state} canEdit={canEdit} />
      <FilePicker inputRef={input} onPick={(files) => void state.upload(files)} />
    </CollapsibleCard>
  );
}

/**
 * R6b: "Add ▾": "Your computer" opens the file picker; "Existing file in CRM" is drawn but off,
 * "Not available yet" (the user's call, 19 Nov: the design's item only toasts "No files in the
 * file manager yet", and master has no file picker for it). Escape and an outside click close.
 */
function AttachAddMenu({
  className,
  uploading,
  onComputer,
}: {
  className: string;
  uploading: boolean;
  onComputer: () => void;
}) {
  const [open, setOpen] = useState(false);
  const wrapRef = useRef<HTMLSpanElement>(null);
  const btnRef = useRef<HTMLButtonElement>(null);
  useEffect(() => {
    if (!open) return;
    const onDown = (e: MouseEvent) => {
      if (!wrapRef.current?.contains(e.target as Node)) setOpen(false);
    };
    const onKey = (e: KeyboardEvent) => {
      if (e.key !== 'Escape') return;
      setOpen(false);
      btnRef.current?.focus();
    };
    document.addEventListener('mousedown', onDown, true);
    window.addEventListener('keydown', onKey);
    return () => {
      document.removeEventListener('mousedown', onDown, true);
      window.removeEventListener('keydown', onKey);
    };
  }, [open]);
  return (
    <span className="att-add" ref={wrapRef}>
      <button
        ref={btnRef}
        type="button"
        className={className}
        aria-haspopup="menu"
        aria-expanded={open}
        disabled={uploading}
        onClick={() => setOpen((o) => !o)}
      >
        {uploading ? 'Uploading…' : 'Add ▾'}
      </button>
      {open ? (
        <span className="att-add__list" role="menu">
          <button
            type="button"
            role="menuitem"
            onClick={() => {
              setOpen(false);
              onComputer();
            }}
          >
            Your computer
          </button>
          <button type="button" role="menuitem" disabled title="Not available yet">
            Existing file in CRM
          </button>
        </span>
      ) : null}
    </span>
  );
}
