'use client';

import Link from 'next/link';
import { useState } from 'react';
import { CrmIcon } from '@/components/crm/CrmIcon';
import type { AssociationCandidate } from '@/features/associations/types';
import { RecordSearchInput } from '@/features/associations/ui/RecordSearchInput';
import { cn } from '@/lib/utils/cn';
import type { AssocCard, AssocSection } from '../associations';

const initials = (name: string) =>
  name
    .split(/\s+/)
    .filter(Boolean)
    .slice(0, 2)
    .map((w) => w[0]!.toUpperCase())
    .join('') || '?';

function Chevron() {
  return (
    <svg className="act-i act-chev" viewBox="0 0 24 24" aria-hidden="true">
      <path
        d="m6 9 6 6 6-6"
        fill="none"
        stroke="currentColor"
        strokeWidth="2"
        strokeLinecap="round"
        strokeLinejoin="round"
      />
    </svg>
  );
}

function Plus() {
  return (
    <svg className="act-i act-i--xs" viewBox="0 0 24 24" aria-hidden="true">
      <path
        d="M12 5v14M5 12h14"
        fill="none"
        stroke="currentColor"
        strokeWidth="2"
        strokeLinecap="round"
      />
    </svg>
  );
}

function Copy() {
  return (
    <svg className="act-i act-i--xs" viewBox="0 0 24 24" aria-hidden="true">
      <path
        d="M9 9h10v11H9zM5 15V4h10"
        fill="none"
        stroke="currentColor"
        strokeWidth="1.8"
        strokeLinejoin="round"
      />
    </svg>
  );
}

function External() {
  return (
    <svg className="act-i act-i--xs" viewBox="0 0 24 24" aria-hidden="true">
      <path
        d="M14 4h6v6M20 4l-9 9M18 14v5H5V6h5"
        fill="none"
        stroke="currentColor"
        strokeWidth="1.8"
        strokeLinecap="round"
        strokeLinejoin="round"
      />
    </svg>
  );
}

function DealIcon() {
  return (
    <svg className="act-i" viewBox="0 0 24 24" aria-hidden="true">
      <path
        d="M3 12l4-4 3 2 3-3 4 1 4 4-5 5-3-2-2 2-4-1z"
        fill="none"
        stroke="currentColor"
        strokeWidth="1.5"
        strokeLinejoin="round"
      />
    </svg>
  );
}

/** The design's empty-section art (activity.js SV.art). */
function Art() {
  return (
    <svg className="act-art" viewBox="0 0 120 100" aria-hidden="true">
      <rect
        x="62"
        y="10"
        width="22"
        height="22"
        rx="4"
        fill="none"
        stroke="var(--act-art-2)"
        strokeWidth="2.5"
      />
      <rect
        x="40"
        y="28"
        width="34"
        height="34"
        rx="6"
        fill="none"
        stroke="var(--act-art-1)"
        strokeWidth="2.5"
      />
      <rect x="50" y="38" width="16" height="16" rx="2" fill="var(--act-art-1)" />
      <rect
        x="20"
        y="52"
        width="30"
        height="30"
        rx="6"
        fill="none"
        stroke="var(--act-art-1)"
        strokeWidth="2.5"
      />
      <rect
        x="28"
        y="60"
        width="14"
        height="14"
        rx="2"
        fill="none"
        stroke="var(--act-art-3)"
        strokeWidth="2.5"
      />
    </svg>
  );
}

export interface CallAssociationsPanelProps {
  sections: AssocSection[];
  /** The caller may change this call's links (the call's edit rule). */
  editable: boolean;
  busy: boolean;
  /** Custom objects' names for the record search ("ticket" / "tickets"). */
  namesOf: (type: string) => { one: string; many: string } | undefined;
  onClose: () => void;
  onRemove: (type: string, id: string) => void;
  /** Links the picked record; resolves true once saved. */
  onAdd: (type: string, record: AssociationCandidate) => Promise<boolean>;
  onCopy: (value: string) => void;
}

/**
 * CGL3: the call page's All associations panel as the design's (activity.php:310-316,
 * activity.js:231-400): collapsible sections with cards and Add; Add opens "Add existing …".
 */
export function CallAssociationsPanel({
  sections,
  editable,
  busy,
  namesOf,
  onClose,
  onRemove,
  onAdd,
  onCopy,
}: CallAssociationsPanelProps) {
  const [closed, setClosed] = useState<ReadonlySet<string>>(new Set());
  const [adding, setAdding] = useState<string | null>(null);
  const [picked, setPicked] = useState<AssociationCandidate | null>(null);
  const addSection = adding ? sections.find((s) => s.type === adding) : undefined;

  const toggle = (type: string) =>
    setClosed((prev) => {
      const next = new Set(prev);
      if (next.has(type)) next.delete(type);
      else next.add(type);
      return next;
    });
  const back = () => {
    setAdding(null);
    setPicked(null);
  };

  const card = (section: AssocSection, c: AssocCard) => (
    <div className="act-acard" key={c.id}>
      <div className="act-acard__h">
        {c.lead === 'avatar' ? <span className="act-av act-av--sm">{initials(c.name)}</span> : null}
        {c.lead === 'logo' ? <span className="act-logo">{initials(c.name)}</span> : null}
        {c.lead === 'deal' ? (
          <span className="act-logo act-logo--round">
            <DealIcon />
          </span>
        ) : null}
        <Link className="act-acard__n" href={c.href}>
          {c.name}
        </Link>
      </div>
      {c.lines.map((l) => (
        <p key={l.label}>
          {l.label}:{' '}
          {l.href ? (
            <a
              className="act-strong"
              href={l.href}
              {...(l.external && { target: '_blank', rel: 'noopener noreferrer' })}
            >
              {l.value}
              {l.external ? (
                <>
                  {' '}
                  <External />
                </>
              ) : null}
            </a>
          ) : (
            <span className="act-strong">{l.value}</span>
          )}
          {l.copy ? (
            <>
              {' '}
              <button
                type="button"
                className="act-icon act-icon--sm"
                aria-label={`Copy ${l.label.toLowerCase()}`}
                onClick={() => onCopy(l.value)}
              >
                <Copy />
              </button>
            </>
          ) : null}
        </p>
      ))}
      {editable ? (
        <button
          type="button"
          className="act-acard__x"
          aria-label={`Remove association with ${c.name}`}
          disabled={busy}
          onClick={() => onRemove(section.type, c.id)}
        >
          <CrmIcon name="x" className="iconSize-14" />
        </button>
      ) : null}
    </div>
  );

  return (
    <>
      <div className="act-ov is-open" onClick={onClose} aria-hidden="true" />
      <aside
        className="act-panel is-open"
        role="dialog"
        aria-modal="true"
        aria-labelledby="actAssocT"
      >
        <header className="act-panel__head">
          <h2 id="actAssocT">
            {addSection ? `Add existing ${addSection.one}` : 'All associations'}
          </h2>
          <button type="button" className="act-icon" aria-label="Close" onClick={onClose}>
            <CrmIcon name="x" className="iconSize-18" />
          </button>
        </header>
        {addSection ? (
          <>
            <div className="act-panel__body act-panel__body--add">
              <RecordSearchInput
                id={`callAssocAdd-${addSection.type}`}
                type={addSection.type}
                names={namesOf(addSection.type)}
                value={picked}
                onPick={setPicked}
                linkedIds={new Set(addSection.cards.map((c) => c.id))}
                disabled={busy}
              />
            </div>
            <footer className="act-panel__foot">
              <button
                type="button"
                className={cn('btn-crm btn-crm--primary', busy && 'is-loading')}
                disabled={busy || !picked}
                onClick={() => {
                  if (!picked) return;
                  void onAdd(addSection.type, picked).then((ok) => {
                    if (ok) back();
                  });
                }}
              >
                Save
              </button>
              <button type="button" className="btn-crm btn-crm--outline" onClick={back}>
                Cancel
              </button>
            </footer>
          </>
        ) : (
          <div className="act-panel__body act-panel__body--assoc">
            {sections.map((s) => {
              const open = !closed.has(s.type);
              return (
                <section key={s.type} className={cn('act-asec', open && 'is-open')}>
                  <div className="act-asec__h">
                    <button
                      type="button"
                      className="act-asec__t"
                      aria-expanded={open}
                      onClick={() => toggle(s.type)}
                    >
                      <Chevron />
                      <span>
                        {s.label} ({s.total})
                      </span>
                    </button>
                    {editable ? (
                      <button
                        type="button"
                        className="act-add"
                        disabled={busy}
                        onClick={() => setAdding(s.type)}
                      >
                        <Plus />
                        Add
                      </button>
                    ) : null}
                  </div>
                  {open ? (
                    <div className="act-asec__b">
                      {s.cards.length ? (
                        s.cards.map((c) => card(s, c))
                      ) : (
                        <div className="act-aempty">
                          <Art />
                          <p>
                            See the {s.type === 'contact' ? 'people' : s.label} associated with this
                            record.
                          </p>
                        </div>
                      )}
                    </div>
                  ) : null}
                </section>
              );
            })}
          </div>
        )}
      </aside>
    </>
  );
}
