'use client';

import { useCallback, useEffect, useMemo, useState } from 'react';
import { Alert } from '@/components/crm/Alert';
import { useConfirm } from '@/components/crm/useConfirm';
import { useToast } from '@/components/crm/ToastProvider';
import {
  archiveAssociationLabel,
  createAssociationLabel,
  listAssociationLabels,
  renameAssociationLabel,
} from '@/features/associations/api.client';
import type { AssociationLabel, AssociationObjectType } from '@/features/associations/types';
import { useCurrentUser } from '@/features/auth/CurrentUser';
import { errorText } from '@/lib/api/errors';
import { cn } from '@/lib/utils/cn';
import { DrawerForm } from './settings-ui';

/** Record pairs that can be linked, in the order the API stores them (first = "a" side). */
const PAIRS: Array<{
  key: string;
  aType: AssociationObjectType;
  bType: AssociationObjectType;
  label: string;
  a: string;
  b: string;
}> = [
  {
    key: 'company:company',
    aType: 'company',
    bType: 'company',
    label: 'Company – Company',
    a: 'a company',
    b: 'the other company',
  },
  {
    key: 'contact:contact',
    aType: 'contact',
    bType: 'contact',
    label: 'Contact – Contact',
    a: 'a contact',
    b: 'the other contact',
  },
  {
    key: 'deal:deal',
    aType: 'deal',
    bType: 'deal',
    label: 'Deal – Deal',
    a: 'a deal',
    b: 'the other deal',
  },
  {
    key: 'company:contact',
    aType: 'company',
    bType: 'contact',
    label: 'Company – Contact',
    a: 'a company',
    b: 'a contact',
  },
  {
    key: 'contact:deal',
    aType: 'contact',
    bType: 'deal',
    label: 'Contact – Deal',
    a: 'a contact',
    b: 'a deal',
  },
  {
    key: 'company:deal',
    aType: 'company',
    bType: 'deal',
    label: 'Company – Deal',
    a: 'a company',
    b: 'a deal',
  },
];

const pairKey = (label: AssociationLabel) => `${label.aType}:${label.bType}`;

/** Empty input: `null` (no inverse), so the label reads the same both ways. */
const optionalText = (value: FormDataEntryValue | null) => String(value ?? '').trim() || null;

/**
 * Settings > Associations: the labels users can put on a link between two record types. A label
 * can have an inverse ("Agency" / "Brand"): the label shows on one record, the inverse on the
 * linked one. Only admins (manage_settings) can change them.
 */
/** QA #450: system labels cannot be edited or archived, so their actions must not look like links. */
const LOCKED_LABEL_STYLE = {
  color: 'var(--text-muted)',
  textDecoration: 'none',
  cursor: 'not-allowed',
};

export function AssociationsSettingsView() {
  const toast = useToast();
  const me = useCurrentUser();
  const canManage = Boolean(me.permissionSet.rules.app.manage_settings);

  const [labels, setLabels] = useState<AssociationLabel[]>([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);
  const [busyId, setBusyId] = useState<string | null>(null);
  const [pairKeyValue, setPairKey] = useState(PAIRS[0]!.key);
  const pair = PAIRS.find((p) => p.key === pairKeyValue) ?? PAIRS[0]!;
  const [createOpen, setCreateOpen] = useState(false);
  const [editOpen, setEditOpen] = useState(false);
  const [editTarget, setEditTarget] = useState<AssociationLabel | null>(null);

  const load = useCallback(async () => {
    setLoading(true);
    try {
      setLabels(await listAssociationLabels());
      setError(null);
    } catch (err) {
      setLabels([]);
      setError(errorText(err));
    } finally {
      setLoading(false);
    }
  }, []);

  useEffect(() => {
    void load();
  }, [load]);

  const rows = useMemo(
    () =>
      labels
        .filter((label) => pairKey(label) === pair.key)
        .sort((x, y) => x.name.localeCompare(y.name)),
    [labels, pair.key],
  );

  const { confirm, dialog: confirmDialog } = useConfirm();

  const onArchive = async (label: AssociationLabel) => {
    if (!canManage || busyId) return;
    const text = label.inverseName ? `${label.name} / ${label.inverseName}` : label.name;
    // #372: in-app confirm instead of the browser's window.confirm.
    const ok = await confirm({
      title: 'Archive association label?',
      message: `Archive "${text}"? Existing links keep the label.`,
      confirmLabel: 'Archive',
      danger: true,
    });
    if (!ok) return;
    setBusyId(label.id);
    try {
      await archiveAssociationLabel(label.id);
      setLabels((current) => current.filter((item) => item.id !== label.id));
      toast('Label archived.', 'success');
    } catch (err) {
      toast(errorText(err), 'danger');
    } finally {
      setBusyId(null);
    }
  };

  return (
    <>
      {confirmDialog}
      <header className="set-head">
        <div>
          <h1 className="set-head__title">Associations</h1>
          <p className="set-head__sub">
            Labels for links between records, e.g. Parent / Child or Agency / Brand.
          </p>
        </div>
      </header>

      {error ? <Alert tone="danger">{error}</Alert> : null}
      {!canManage ? (
        <Alert tone="warning">You can view these settings, but only admins can change them.</Alert>
      ) : null}

      <nav className="set-tabs set-tabs--boxed" role="tablist" aria-label="Association pairs">
        {PAIRS.map((option) => (
          <button
            key={option.key}
            type="button"
            className={cn('set-tab', option.key === pair.key && 'active')}
            role="tab"
            aria-selected={option.key === pair.key}
            onClick={() => setPairKey(option.key)}
          >
            {option.label}
          </button>
        ))}
      </nav>

      <section role="tabpanel" className="crm-mt-3">
        <div className="set-card__head">
          <div>
            <h2 className="set-block__title">{pair.label} labels</h2>
            <p className="set-block__sub">
              The label shows on {pair.a} for {pair.b}; the inverse label shows on {pair.b} for{' '}
              {pair.a}.
            </p>
          </div>
          <div className="set-head__actions">
            <button
              type="button"
              className="btn-crm btn-crm--primary btn-crm--sm"
              disabled={!canManage}
              onClick={() => setCreateOpen(true)}
            >
              Create label
            </button>
          </div>
        </div>

        <div className="card set-table-card">
          <table className="set-table su-table">
            <thead>
              <tr>
                <th>Label</th>
                <th>Inverse label</th>
                <th className="su-num">Limit per record</th>
                <th>Type</th>
                <th className="col-actions">
                  <span className="crm-visually-hidden">Actions</span>
                </th>
              </tr>
            </thead>
            <tbody>
              {loading ? (
                <tr>
                  <td colSpan={5} className="crm-text-body-secondary">
                    Loading labels...
                  </td>
                </tr>
              ) : rows.length === 0 ? (
                <tr>
                  <td colSpan={5} className="crm-text-body-secondary">
                    No labels for this pair yet.
                  </td>
                </tr>
              ) : (
                rows.map((label) => (
                  <tr key={label.id}>
                    <td data-label="Label" className="crm-fw-semibold">
                      {label.name}
                    </td>
                    <td data-label="Inverse label">
                      {label.inverseName ?? (
                        <span className="crm-text-body-secondary">Same both ways</span>
                      )}
                    </td>
                    <td data-label="Limit per record" className="su-num">
                      {label.maxPerRecord ?? '—'}
                    </td>
                    <td data-label="Type">
                      <span className="badge">
                        {label.category === 'system' ? 'System' : 'Custom'}
                      </span>
                    </td>
                    <td className="col-actions" data-label="Actions">
                      <div style={{ display: 'flex', gap: 10, justifyContent: 'flex-end' }}>
                        <button
                          type="button"
                          className="link"
                          disabled={
                            !canManage || busyId === label.id || label.category === 'system'
                          }
                          title={
                            label.category === 'system'
                              ? 'System labels cannot be edited'
                              : undefined
                          }
                          style={label.category === 'system' ? LOCKED_LABEL_STYLE : undefined}
                          onClick={() => {
                            setEditTarget(label);
                            setEditOpen(true);
                          }}
                        >
                          Edit
                        </button>
                        <button
                          type="button"
                          className="link"
                          disabled={
                            !canManage || busyId === label.id || label.category === 'system'
                          }
                          title={
                            label.category === 'system'
                              ? 'System labels cannot be archived'
                              : undefined
                          }
                          style={label.category === 'system' ? LOCKED_LABEL_STYLE : undefined}
                          onClick={() => void onArchive(label)}
                        >
                          Archive
                        </button>
                      </div>
                    </td>
                  </tr>
                ))
              )}
            </tbody>
          </table>
        </div>
      </section>

      <DrawerForm
        key={`create-${pair.key}`}
        id="create-association-label"
        title={`Create ${pair.label} label`}
        open={createOpen}
        onClose={() => setCreateOpen(false)}
        submitLabel="Create"
        onSave={async (formData) => {
          const name = String(formData.get('name') ?? '').trim();
          const inverseName = optionalText(formData.get('inverseName'));
          const limitText = String(formData.get('maxPerRecord') ?? '').trim();
          if (!name) {
            toast('Label is required.', 'danger');
            return false;
          }
          try {
            const created = await createAssociationLabel({
              aType: pair.aType,
              bType: pair.bType,
              name,
              inverseName,
              ...(limitText ? { maxPerRecord: Number(limitText) } : {}),
            });
            setLabels((current) => [...current, created]);
            return 'Label created';
          } catch (err) {
            toast(errorText(err), 'danger');
            return false;
          }
        }}
      >
        <div className="field field--full">
          <label className="field__label" htmlFor="cal-name">
            Label
          </label>
          <input className="input" id="cal-name" name="name" required maxLength={191} />
          <p className="field__help">
            Shown on {pair.a} for {pair.b}, e.g. Parent Company.
          </p>
        </div>

        <div className="field field--full">
          <label className="field__label" htmlFor="cal-inverse">
            Inverse label (optional)
          </label>
          <input className="input" id="cal-inverse" name="inverseName" maxLength={191} />
          <p className="field__help">
            Shown on {pair.b} for {pair.a}, e.g. Child Company. Leave empty to show the same label
            on both.
          </p>
        </div>

        <div className="field field--full">
          <label className="field__label" htmlFor="cal-limit">
            Limit per record (optional)
          </label>
          <input
            className="input"
            id="cal-limit"
            type="number"
            name="maxPerRecord"
            min={1}
            max={10000}
          />
          <p className="field__help">Most links with this label one record may have.</p>
        </div>
      </DrawerForm>

      <DrawerForm
        key={editTarget?.id ?? 'no-label-edit'}
        id="edit-association-label"
        title={editTarget ? `Edit ${editTarget.name}` : 'Edit label'}
        open={editOpen}
        onClose={() => {
          setEditOpen(false);
          setEditTarget(null);
        }}
        keep
        onSave={async (formData) => {
          if (!editTarget) return false;
          const name = String(formData.get('name') ?? '').trim();
          const inverseName = optionalText(formData.get('inverseName'));
          if (!name) {
            toast('Label is required.', 'danger');
            return false;
          }
          try {
            const updated = await renameAssociationLabel(editTarget.id, { name, inverseName });
            setLabels((current) =>
              current.map((label) => (label.id === updated.id ? updated : label)),
            );
            return 'Label updated';
          } catch (err) {
            toast(errorText(err), 'danger');
            return false;
          }
        }}
      >
        <div className="field field--full">
          <label className="field__label" htmlFor="eal-name">
            Label
          </label>
          <input
            className="input"
            id="eal-name"
            name="name"
            required
            maxLength={191}
            defaultValue={editTarget?.name ?? ''}
          />
        </div>

        <div className="field field--full">
          <label className="field__label" htmlFor="eal-inverse">
            Inverse label (optional)
          </label>
          <input
            className="input"
            id="eal-inverse"
            name="inverseName"
            maxLength={191}
            defaultValue={editTarget?.inverseName ?? ''}
          />
          <p className="field__help">Leave empty to show the same label on both records.</p>
        </div>
      </DrawerForm>
    </>
  );
}
