'use client';

import { useState } from 'react';
import { useToast } from '@/components/crm/ToastProvider';
import {
  archiveAssociationLabel,
  renameAssociationLabel,
} from '@/features/associations/api.client';
import type { AssociationLabel } from '@/features/associations/types';
import { errorText } from '@/lib/api/errors';
import { cn } from '@/lib/utils/cn';
import { LIMIT_MAX, limitProblem } from '../associationLimit';
import { byText, labelLimit, labelsBetween, type DataModel, type DmObject } from '../model';
import { DmIcon } from './icons';
import { Modal } from './primitives';
import { nameInText } from '@/features/objects/paths';

/**
 * Data Model > an object's associations, row Actions (as in HubSpot): manage the labels of one
 * pair, edit their per-record limits, and see the ids an integration needs. Everything acts on
 * the pair as `from` reads it; labels are stored a -> b, so the sides are swapped when `from` is
 * the b-side object.
 */

/** A label's two names as `from` reads them: its own and the other side's ('' = the same). */
function sidesOf(l: AssociationLabel, from: string): { mine: string; theirs: string } {
  if (l.aType === from) return { mine: l.name, theirs: l.inverseName ?? '' };
  return l.inverseName ? { mine: l.inverseName, theirs: l.name } : { mine: l.name, theirs: '' };
}

/** The stored name and inverse for what `from` typed on its side and the other one. */
function storedOf(
  l: AssociationLabel,
  from: string,
  mine: string,
  theirs: string,
): { name: string; inverseName: string | null } {
  if (l.aType === from || !theirs) return { name: mine, inverseName: theirs || null };
  return { name: theirs, inverseName: mine };
}

const isSystem = (l: AssociationLabel) => l.category === 'system';
const SYSTEM_HINT = 'System labels keep their name and limit';

/** The object a label's limit counts on: its a-side, as the API stores it. */
function limitedSide(model: DataModel, l: AssociationLabel): DmObject | undefined {
  return model.objects.find((o) => o.key === l.aType);
}

type View =
  | { kind: 'list' }
  | { kind: 'edit'; label: AssociationLabel }
  | { kind: 'archive'; label: AssociationLabel };

/** "Manage all association labels": the pair's labels, renamed or archived here. */
export function ManageLabelsModal({
  model,
  from,
  to,
  onClose,
  onCreate,
  onChanged,
}: {
  model: DataModel;
  from: DmObject;
  to: DmObject;
  onClose: () => void;
  /** Opens "Create association label" for the pair. */
  onCreate: () => void;
  /** The labels changed: load them again. */
  onChanged: () => Promise<void>;
}) {
  const toast = useToast();
  const [view, setView] = useState<View>({ kind: 'list' });
  const [mine, setMine] = useState('');
  const [theirs, setTheirs] = useState('');
  const labels = [...labelsBetween(model, from.key, to.key)].sort((a, b) =>
    byText(sidesOf(a, from.key).mine, sidesOf(b, from.key).mine),
  );
  const back = () => setView({ kind: 'list' });

  if (view.kind === 'edit') {
    const l = view.label;
    return (
      <Modal
        title="Edit association label"
        okLabel="Save"
        okDisabled={!mine.trim()}
        cancelLabel="Back"
        onClose={back}
        onOk={async () => {
          try {
            await renameAssociationLabel(l.id, storedOf(l, from.key, mine.trim(), theirs.trim()));
            toast('Association label saved', 'success');
            await onChanged();
            back();
          } catch (err) {
            toast(errorText(err), 'danger');
          }
          return false;
        }}
      >
        <p className="dm-muted">
          {from.name} to {to.name}
        </p>
        <label className="dm-field">
          <span className="dm-field__label">Label *</span>
          <span className="dm-field__hint">
            How a {nameInText(from.singular)} shows a linked {nameInText(to.singular)}.
          </span>
          <input
            className="dm-input"
            type="text"
            value={mine}
            maxLength={191}
            autoFocus
            onChange={(e) => setMine(e.target.value)}
          />
        </label>
        <label className="dm-field">
          <span className="dm-field__label">Label from the other side</span>
          <span className="dm-field__hint">Leave empty when it reads the same both ways.</span>
          <input
            className="dm-input"
            type="text"
            value={theirs}
            maxLength={191}
            onChange={(e) => setTheirs(e.target.value)}
          />
        </label>
      </Modal>
    );
  }

  if (view.kind === 'archive') {
    const l = view.label;
    return (
      <Modal
        title="Archive association label?"
        okLabel="Archive"
        danger
        onClose={back}
        cancelLabel="Back"
        onOk={async () => {
          try {
            await archiveAssociationLabel(l.id);
            toast(`"${sidesOf(l, from.key).mine}" archived`, 'success');
            await onChanged();
            back();
          } catch (err) {
            toast(errorText(err), 'danger');
          }
          return false;
        }}
      >
        <p className="dm-muted">
          <b>{sidesOf(l, from.key).mine}</b> can&apos;t be picked on new links any more. Links that
          have it keep it.
        </p>
      </Modal>
    );
  }

  return (
    <Modal
      title={`${from.name} to ${to.name} labels`}
      okLabel="Done"
      noCancel
      wide
      onClose={onClose}
      onOk={() => undefined}
    >
      <div className="dm-labels-head">
        <p className="dm-muted">
          How {nameInText(from.name)} and {nameInText(to.name)} are linked.
        </p>
        <button
          type="button"
          className="dm-btn dm-btn--soft dm-btn--sm"
          onClick={() => {
            onClose();
            onCreate();
          }}
        >
          <DmIcon name="plus" size={14} />
          Create association label
        </button>
      </div>
      {labels.length ? (
        <table className="dm-labels">
          <thead>
            <tr>
              <th>Label</th>
              <th>From the other side</th>
              <th>Limit</th>
              <th>
                <span className="crm-visually-hidden">Actions</span>
              </th>
            </tr>
          </thead>
          <tbody>
            {labels.map((l) => {
              const side = sidesOf(l, from.key);
              return (
                <tr key={l.id}>
                  <td>
                    {side.mine}
                    {isSystem(l) && (
                      <span className="dm-chip dm-chip--sm dm-chip--faint">System</span>
                    )}
                  </td>
                  <td>{side.theirs || <span className="dm-muted">Same both ways</span>}</td>
                  <td>{labelLimit(l)}</td>
                  <td className="dm-labels__actions">
                    <button
                      type="button"
                      className="dm-btn dm-btn--outline dm-btn--xxs"
                      disabled={isSystem(l)}
                      title={isSystem(l) ? SYSTEM_HINT : undefined}
                      onClick={() => {
                        setMine(side.mine);
                        setTheirs(side.theirs);
                        setView({ kind: 'edit', label: l });
                      }}
                    >
                      Edit
                    </button>
                    <button
                      type="button"
                      className="dm-btn dm-btn--outline dm-btn--xxs"
                      disabled={isSystem(l)}
                      title={isSystem(l) ? SYSTEM_HINT : undefined}
                      onClick={() => setView({ kind: 'archive', label: l })}
                    >
                      Archive
                    </button>
                  </td>
                </tr>
              );
            })}
          </tbody>
        </table>
      ) : (
        <p className="dm-muted">No labels yet. Records are linked without one.</p>
      )}
    </Modal>
  );
}

/** "Edit association limit": how many links with each label one record may have. */
export function EditLimitsModal({
  model,
  from,
  to,
  onClose,
  onChanged,
}: {
  model: DataModel;
  from: DmObject;
  to: DmObject;
  onClose: () => void;
  onChanged: () => Promise<void>;
}) {
  const toast = useToast();
  const labels = labelsBetween(model, from.key, to.key);
  const [limits, setLimits] = useState<Record<string, string>>(() =>
    Object.fromEntries(labels.map((l) => [l.id, l.maxPerRecord ? String(l.maxPerRecord) : ''])),
  );
  // A refused limit ("A record already has 3 links with this label"), under its own box.
  const [errors, setErrors] = useState<Record<string, string>>({});
  // Boxes with text the number box can't read ("--1"), which it reports as empty.
  const [bad, setBad] = useState<Record<string, boolean>>({});
  const valueOf = (id: string) => (limits[id]?.trim() ? Number(limits[id]) : null);
  // #559: a typed limit the API would refuse is said under its box (the user's call, 17 Nov).
  const problemOf = (id: string) => limitProblem(limits[id] ?? '', bad[id]);
  const valid = labels.every((l) => !problemOf(l.id));
  const changed = labels.filter((l) => valueOf(l.id) !== (l.maxPerRecord ?? null));
  return (
    <Modal
      title="Edit association limit"
      okLabel="Save"
      okDisabled={!labels.length || !valid || !changed.length}
      onClose={onClose}
      onOk={async () => {
        let saving: AssociationLabel | undefined;
        try {
          for (const l of changed) {
            saving = l;
            await renameAssociationLabel(l.id, { maxPerRecord: valueOf(l.id) });
          }
          toast('Association limits saved', 'success');
          await onChanged();
        } catch (err) {
          const failed = saving;
          if (failed) {
            setErrors((cur) => ({ ...cur, [failed.id]: errorText(err) }));
            // Once the error shows: the box with its message in view, ready to change.
            window.requestAnimationFrame(() => {
              const input = document.getElementById(`dm-limit-${failed.id}`);
              input?.focus();
              input?.closest('.dm-field')?.scrollIntoView({ block: 'nearest' });
            });
          }
          toast(errorText(err), 'danger');
          await onChanged();
          return false;
        }
      }}
    >
      <p className="dm-muted">
        {from.name} to {to.name}. Records link without a limit; a label can allow only so many links
        per record. Empty: no limit.
      </p>
      {labels.length ? (
        labels.map((l) => {
          const limited = limitedSide(model, l);
          const other = model.objects.find(
            (o) => o.key === (l.aType === limited?.key ? l.bType : l.aType),
          );
          // What's typed first; the API's refusal of the last save once the box is valid.
          const shown = problemOf(l.id) ?? errors[l.id];
          return (
            <label key={l.id} className="dm-field">
              <span className="dm-field__label">{sidesOf(l, from.key).mine}</span>
              <span className="dm-field__hint">
                {isSystem(l)
                  ? SYSTEM_HINT
                  : `Each ${limited ? nameInText(limited.singular) : 'record'} can have this label on at most this many ${other ? nameInText(other.name) : 'records'}.`}
              </span>
              <input
                id={`dm-limit-${l.id}`}
                className={cn('dm-input', shown && 'is-invalid')}
                type="number"
                min={1}
                max={LIMIT_MAX}
                value={limits[l.id] ?? ''}
                placeholder="No limit"
                disabled={isSystem(l)}
                aria-invalid={Boolean(shown)}
                // React's onChange skips an input event that leaves the value "" (unreadable
                // text in an empty box, or the box cleared after it): badInput is read here.
                onInput={(e) => {
                  const badInput = e.currentTarget.validity.badInput;
                  setBad((cur) => ({ ...cur, [l.id]: badInput }));
                }}
                onChange={(e) => {
                  setLimits((cur) => ({ ...cur, [l.id]: e.target.value }));
                  setErrors((cur) => {
                    const next = { ...cur };
                    delete next[l.id];
                    return next;
                  });
                }}
              />
              {shown && <span className="dm-field__error">{shown}</span>}
            </label>
          );
        })
      ) : (
        <p className="dm-muted">
          This pair has no labels, so links have no limit. Create a label to set one.
        </p>
      )}
    </Modal>
  );
}

/** "View API details": the ids an integration uses for the pair and each label. */
export function ApiDetailsModal({
  model,
  from,
  to,
  onClose,
}: {
  model: DataModel;
  from: DmObject;
  to: DmObject;
  onClose: () => void;
}) {
  const labels = labelsBetween(model, from.key, to.key);
  const query = `aType=${encodeURIComponent(from.key)}&bType=${encodeURIComponent(to.key)}`;
  return (
    <Modal
      title="API details"
      okLabel="Close"
      noCancel
      wide
      onClose={onClose}
      onOk={() => undefined}
    >
      <table className="dm-labels">
        <tbody>
          <tr>
            <th>{from.name}</th>
            <td>
              <code>{from.key}</code> · Object type ID <code>{from.typeId}</code>
            </td>
          </tr>
          <tr>
            <th>{to.name}</th>
            <td>
              <code>{to.key}</code> · Object type ID <code>{to.typeId}</code>
            </td>
          </tr>
          <tr>
            <th>Labels</th>
            <td>
              <code>GET /api/v1/association-labels?{query}</code>
            </td>
          </tr>
        </tbody>
      </table>
      {labels.length ? (
        <table className="dm-labels">
          <thead>
            <tr>
              <th>Label</th>
              <th>Label ID</th>
              <th>HubSpot type IDs</th>
            </tr>
          </thead>
          <tbody>
            {labels.map((l) => (
              <tr key={l.id}>
                <td>{sidesOf(l, from.key).mine}</td>
                <td>
                  <code>{l.id}</code>
                </td>
                <td>
                  {l.hubspotTypeId || l.hubspotInverseTypeId ? (
                    <code>
                      {[l.hubspotTypeId, l.hubspotInverseTypeId].filter(Boolean).join(' / ')}
                    </code>
                  ) : (
                    <span className="dm-muted">--</span>
                  )}
                </td>
              </tr>
            ))}
          </tbody>
        </table>
      ) : (
        <p className="dm-muted">The pair has no labels yet.</p>
      )}
    </Modal>
  );
}
