'use client';

import { useState } from 'react';
import { useToast } from '@/components/crm/ToastProvider';
import {
  updateCustomProperty,
  type CustomPropertyDefinition,
} from '@/features/custom-properties/api.client';
import { updateObjectDefinition } from '@/features/objects/api.client';
import { renameObject, resetObjectName, type LabelledObject } from '@/features/objects/labels';
import { errorText } from '@/lib/api/errors';
import { cn } from '@/lib/utils/cn';
import {
  BUILT_IN_OBJECTS,
  canRename,
  isCrmDefined,
  isRenamableBuiltIn,
  type DmObject,
} from '../model';
import {
  changedObjectNames,
  nameClashFromError,
  objectNameClash,
  type NameClash,
} from '../objectNames';
import { NameClashError } from './NameClashError';
import { Drawer, DrawerHead, Tip } from './primitives';

const escapeRe = (s: string) => s.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');

/**
 * QA 18 Nov (#278): a property label with the object's old names swapped for the new ones, as
 * HubSpot's Edit object does ("Contact owner" -> "Patient owner"). The plural is matched before
 * the singular, in one pass; a lowercase mention stays lowercase.
 */
export function relabel(
  label: string,
  from: { singular: string; plural: string },
  to: { singular: string; plural: string },
): string {
  const names = [from.plural, from.singular].filter(Boolean).map(escapeRe);
  if (!names.length) return label;
  return label.replace(new RegExp(names.join('|'), 'gi'), (m) => {
    const next = m.toLowerCase() === from.plural.toLowerCase() ? to.plural : to.singular;
    return m === m.toLowerCase() ? next.toLowerCase() : next;
  });
}

/**
 * "Edit object" (HUB-603), as in HubSpot's side panel: the singular and plural names of a custom
 * object (object definitions API) or of Contacts, Companies and Deals (object labels API), the
 * object type ID, and a custom object's description. A CRM-defined object's plural name
 * (Contacts, Companies, Deals, Leads, Tickets...) stays as HubSpot names it. Objects whose names
 * are fixed (activities, objects with no records here, or a CRM-defined object not switched on
 * yet) open read-only, saying why. Only the names
 * change; the object type stays. Both APIs tell the navigation to reload the names.
 */
export function EditObjectPanel({
  object: o,
  objects,
  properties = [],
  onClose,
  onSaved,
}: {
  object: DmObject;
  /** Every object of the data model, for "An object named … already exists" (#561). */
  objects: DmObject[];
  /** The object's live fields, for the Properties label table (#278). */
  properties?: CustomPropertyDefinition[];
  onClose: () => void;
  onSaved: () => void;
}) {
  const toast = useToast();
  const builtIn = isRenamableBuiltIn(o);
  const editable = canRename(o);
  // QA #278: as in HubSpot, a CRM-defined object's plural name is locked, Contacts, Companies and
  // Deals included; their Reset to default still restores it.
  const fixedPlural = builtIn || Boolean(o.definition && isCrmDefined(o.definition));
  const defaults = BUILT_IN_OBJECTS.find((b) => b.key === o.key);
  const [singular, setSingular] = useState(o.singular);
  const [plural, setPlural] = useState(o.name);
  // A custom object's own description; the built-in one (`o.desc`) is only a hint, so saving
  // unchanged never stores it.
  const [description, setDescription] = useState(
    o.definition ? (o.definition.description ?? '') : o.desc,
  );
  const [busy, setBusy] = useState(false);
  /** #278: replacement labels the user typed, by field id. */
  const [edited, setEdited] = useState<Record<string, string>>({});
  const singularMissing = !singular.trim();
  const pluralMissing = !plural.trim();
  const isDefaultName = defaults
    ? singular.trim() === defaults.singular && plural.trim() === defaults.name
    : true;
  // #561: a changed name another object uses. As the API: only the names that change, and going
  // back to Contacts / Companies / Deals' default names is a reset, never refused.
  const [serverClash, setServerClash] = useState<NameClash | null>(null);
  const nameClash =
    (editable && !(builtIn && isDefaultName)
      ? objectNameClash(objects, changedObjectNames(o, singular, plural), o.key)
      : null) ?? serverClash;

  // #278: HubSpot's Properties section: the fields whose labels name the object, with the label
  // each takes (the new names swapped in unless typed over). Built-in fields keep theirs.
  const from = { singular: o.singular, plural: o.name };
  const to = { singular: singular.trim(), plural: plural.trim() };
  const renamedTo =
    editable &&
    Boolean(to.singular) &&
    Boolean(to.plural) &&
    (to.singular !== from.singular || to.plural !== from.plural);
  const mentions = new RegExp([from.plural, from.singular].map(escapeRe).join('|'), 'i');
  const named = properties.filter((p) => !p.standard && !p.archived && mentions.test(p.label));
  const labelOf = (p: CustomPropertyDefinition) =>
    edited[p.id] ?? (renamedTo ? relabel(p.label, from, to) : p.label);

  const save = async () => {
    if (busy || singularMissing || pluralMissing || nameClash) return;
    const body = { singularLabel: singular.trim(), pluralLabel: plural.trim() };
    const newDescription = description.trim() || null;
    const namesChanged = body.singularLabel !== o.singular || body.pluralLabel !== o.name;
    const descriptionChanged =
      Boolean(o.definition) && newDescription !== (o.definition?.description ?? null);
    if (!namesChanged && !descriptionChanged) {
      onClose();
      return;
    }
    setBusy(true);
    try {
      if (o.definition) {
        await updateObjectDefinition(o.definition.id, {
          ...(namesChanged && body),
          ...(descriptionChanged && { description: newDescription }),
        });
      } else if (builtIn && o.renamed && isDefaultName) {
        // Back to the CRM's own names: stored as "not renamed" again.
        await resetObjectName(o.key as LabelledObject);
      } else if (builtIn) {
        await renameObject(o.key as LabelledObject, body);
      }
      // #278: then the fields whose labels follow the new names.
      const relabelled = renamedTo
        ? named.filter((p) => labelOf(p).trim() && labelOf(p).trim() !== p.label)
        : [];
      const failed: string[] = [];
      for (const p of relabelled) {
        try {
          await updateCustomProperty(p.id, { label: labelOf(p).trim() });
        } catch {
          failed.push(p.label);
        }
      }
      if (failed.length) {
        toast(
          `Object updated, but ${failed.length === 1 ? 'this label' : 'these labels'} didn't change: ${failed.join(', ')}`,
          'danger',
        );
      } else toast('Object updated', 'success');
      onSaved();
      onClose();
    } catch (err) {
      const clash = nameClashFromError(err);
      if (clash) setServerClash(clash);
      else toast(errorText(err), 'danger');
    } finally {
      setBusy(false);
    }
  };

  const why = o.deactivated
    ? 'Activate the object to change its name.'
    : "This object's name can't be changed.";

  return (
    <Drawer open onClose={onClose} label="Edit object">
      <DrawerHead title="Edit object" onClose={onClose} />
      <div className="dm-drawer__body">
        {!editable && <p className="dm-co__lead">{why}</p>}
        <label className="dm-field">
          <span className="dm-field__label">Object name (Singular) *</span>
          <input
            className={cn(
              'dm-input',
              editable && (singularMissing || nameClash?.field === 'singular') && 'is-invalid',
            )}
            type="text"
            value={singular}
            maxLength={100}
            autoFocus={editable}
            disabled={!editable}
            aria-invalid={editable && (singularMissing || nameClash?.field === 'singular')}
            onChange={(e) => {
              setSingular(e.target.value);
              setServerClash(null);
            }}
          />
          {editable && singularMissing && (
            <span className="dm-field__error">Enter the singular name.</span>
          )}
          <NameClashError clash={nameClash} field="singular" />
        </label>
        {/* #278: always offered for Contacts, Companies and Deals, as in HubSpot. */}
        {builtIn && defaults && editable && (
          <button
            type="button"
            className="dm-link dm-co__reset"
            disabled={isDefaultName}
            onClick={() => {
              setSingular(defaults.singular);
              setPlural(defaults.name);
              setServerClash(null);
            }}
          >
            Reset to default
          </button>
        )}
        <label className="dm-field">
          <span className="dm-field__label">Object name (Plural) *</span>
          <input
            className={cn(
              'dm-input',
              editable &&
                !fixedPlural &&
                (pluralMissing || nameClash?.field === 'plural') &&
                'is-invalid',
            )}
            type="text"
            value={plural}
            maxLength={100}
            disabled={!editable || fixedPlural}
            title={fixedPlural ? "A CRM-defined object's plural name can't be changed" : undefined}
            onChange={(e) => {
              setPlural(e.target.value);
              setServerClash(null);
            }}
          />
          {editable && !fixedPlural && pluralMissing && (
            <span className="dm-field__error">Enter the plural name.</span>
          )}
          <NameClashError clash={nameClash} field="plural" />
        </label>
        <p className="dm-co-meta">
          Object type ID: <strong>{o.typeId}</strong>
        </p>
        <label className="dm-field">
          <span className="dm-field__label">Description</span>
          <textarea
            className="dm-textarea"
            rows={3}
            value={description}
            placeholder={o.definition ? o.desc : undefined}
            maxLength={2000}
            disabled={!o.definition}
            onChange={(e) => setDescription(e.target.value)}
          />
        </label>
        {renamedTo && named.length > 0 && (
          <>
            <h3 className="dm-co__h">Properties</h3>
            <p className="dm-co__p">
              Relevant property labels will be adjusted to match the new object name (opt out is
              available).{' '}
              <Tip text="Change a replacement label to keep your own, or reset them all to the defaults." />
            </p>
            <button
              type="button"
              className="dm-link"
              disabled={!Object.keys(edited).length}
              onClick={() => setEdited({})}
            >
              Reset to default labels
            </button>
            <div className="dm-co-map">
              <table>
                <thead>
                  <tr>
                    <th>Object type</th>
                    <th>Current property</th>
                    <th aria-label="becomes" />
                    <th>Replacement property</th>
                  </tr>
                </thead>
                <tbody>
                  {named.map((p) => (
                    <tr key={p.id}>
                      <td>{o.name}</td>
                      <td>{p.label}</td>
                      <td className="dm-co-map__arrow">→</td>
                      <td>
                        <input
                          className="dm-input dm-input--sm"
                          type="text"
                          value={labelOf(p)}
                          maxLength={100}
                          aria-label={`Replacement for ${p.label}`}
                          onChange={(e) => setEdited((x) => ({ ...x, [p.id]: e.target.value }))}
                        />
                      </td>
                    </tr>
                  ))}
                </tbody>
              </table>
            </div>
          </>
        )}
        {editable && (
          <p className="dm-field__hint">
            You&apos;ll see the new names in most areas of the CRM. Internal names don&apos;t
            change: links, imports and the API keep using <code>{o.key}</code>.
          </p>
        )}
      </div>
      <div className="dm-drawer__foot">
        {editable ? (
          <>
            <button
              type="button"
              className={cn('dm-btn dm-btn--primary', busy && 'is-loading')}
              disabled={busy || singularMissing || pluralMissing || Boolean(nameClash)}
              onClick={() => void save()}
            >
              Save
            </button>
            <button type="button" className="dm-btn dm-btn--outline" onClick={onClose}>
              Cancel
            </button>
          </>
        ) : (
          <button type="button" className="dm-btn dm-btn--outline" onClick={onClose}>
            Close
          </button>
        )}
      </div>
    </Drawer>
  );
}
