'use client';

import {
  isLockedField,
  lockedFieldTitle,
  type CustomPropertyDefinition,
} from '@/features/custom-properties/api.client';
import { choiceOptions as fieldChoices } from '@/features/custom-properties/choices';
import {
  crmUserChoices,
  crmUserText,
  isMultiUserField,
  ownerIdsOf,
} from '@/features/custom-properties/crm-user';
import { hasTeamLimit, useTeamOptions } from '@/features/custom-properties/useTeamOptions';
import { useOwners } from '@/features/owners/useOwners';
import { applyPropertyLogic, usePropertyLogic } from '@/features/custom-properties/logic';
import type { TeamOption } from '@/features/members/api.client';
import type { Owner } from '@/features/owners/api.client';
import type { CustomProperties } from '@/types/api';
import {
  currencySymbol,
  displayControl,
  formatPercent,
  fromPercent,
  isPercent,
  toPercent,
  useBusinessCurrency,
} from '@/features/custom-properties/field-types';
import { PropertyHistoryButton } from '@/features/property-history/PropertyHistoryButton';
import {
  DesignPropertyRow,
  useDesignPropertyRow,
} from '@/features/record-tools/ui/AllPropertiesDesign';
import { InlineDropdown, InlineEdit } from './InlineEdit';
import { fromLocalInput, TEXTAREA_STYLE, toLocalInput } from './shared';

/**
 * Custom fields (GET /custom-properties?objectType=contact) on the contact page: showing
 * their values and editing them. Stored values (packages/core custom-properties/values.ts):
 * text/textarea/select/date as strings, datetime as an ISO instant, number, boolean, and
 * multiselect as string[].
 */

type StoredValue = CustomProperties[string];

/** What an input holds: text for most types, a list for multiselect ('' = empty). */
export type CustomUiValue = string | string[];

export function toUiValue(
  def: CustomPropertyDefinition,
  stored: StoredValue | undefined,
  timeZone: string,
): CustomUiValue {
  if (def.type === 'multiselect') return Array.isArray(stored) ? stored.map(String) : [];
  // DMG9: a multiple users field edits its list of user ids.
  if (isMultiUserField(def)) return ownerIdsOf(stored);
  if (stored === undefined || stored === null) return '';
  if (def.type === 'boolean') return stored === true ? 'true' : stored === false ? 'false' : '';
  if (def.type === 'datetime' && typeof stored === 'string') {
    const date = new Date(stored);
    return Number.isNaN(date.getTime()) ? '' : toLocalInput(date, timeZone);
  }
  if (isPercent(def) && Number.isFinite(Number(stored))) return String(toPercent(Number(stored)));
  return Array.isArray(stored) ? stored.join(', ') : String(stored);
}

export function sameUiValue(a: CustomUiValue, b: CustomUiValue): boolean {
  if (Array.isArray(a) || Array.isArray(b)) {
    const x = Array.isArray(a) ? a : [a];
    const y = Array.isArray(b) ? b : [b];
    return x.length === y.length && x.every((v, i) => v === y[i]);
  }
  return a === b;
}

/** The value to send in `customProperties` (`null` clears it), or an error to show. */
export function fromUiValue(
  def: CustomPropertyDefinition,
  ui: CustomUiValue,
  timeZone: string,
): { value: StoredValue | null } | { error: string } {
  if (Array.isArray(ui)) return { value: ui.length ? ui : null };
  const text = ui.trim();
  if (!text) return { value: null };
  switch (def.type) {
    case 'number': {
      // A percentage may be typed with its sign ("25%"); the field shows the sign next to it.
      const n = Number(isPercent(def) ? text.replace(/\s*%$/, '') : text);
      if (!Number.isFinite(n)) return { error: `${def.label} must be a number` };
      return { value: isPercent(def) ? fromPercent(n) : n };
    }
    case 'boolean':
      return { value: text === 'true' };
    case 'datetime': {
      const iso = fromLocalInput(text, timeZone);
      return iso ? { value: iso } : { error: `${def.label} needs a date and time` };
    }
    default:
      return { value: text };
  }
}

/**
 * `customProperties` for a create body from the inputs the user filled (empty ones are left
 * out), or an error to show (a bad value, or an empty required field).
 */
export function customValuesForCreate(
  defs: CustomPropertyDefinition[],
  values: Record<string, CustomUiValue>,
  timeZone: string,
): { value: CustomProperties } | { error: string } {
  const out: CustomProperties = {};
  for (const def of defs) {
    const ui = values[def.name];
    const result = ui === undefined ? { value: null } : fromUiValue(def, ui, timeZone);
    if ('error' in result) return result;
    if (result.value === null) {
      if (def.required) return { error: `${def.label} is required` };
      continue;
    }
    out[def.name] = result.value;
  }
  return { value: out };
}

/** Inputs for every custom field, for the create drawers (`.field` + label, one per row). */
export function CustomFieldsForm({
  defs,
  values,
  onChange,
  idPrefix,
  timeZone,
  designLabels = false,
  designSelects = false,
  errors,
}: {
  defs: CustomPropertyDefinition[];
  values: Record<string, CustomUiValue>;
  onChange: (name: string, value: CustomUiValue) => void;
  idPrefix: string;
  timeZone: string;
  /**
   * The 28 Oct design's labels (create-form.js:136): the required mark joined to the label
   * (`.cf-req`), and no "Custom fields" heading, as the fields sit in the form's own order. Only
   * the Create Company panel passes it (B3).
   */
  designLabels?: boolean;
  /**
   * The 28 Oct design's dropdowns (create-form.js:120-121, :143-146): every single-choice field
   * is a dropdown starting at "Select", including those set to Radio select. Only the Create
   * Company panel passes it (QA 3.1: Type and Lifecycle stage).
   */
  designSelects?: boolean;
  /**
   * Messages by `custom.<name>`, each shown under its field with the field marked invalid, as the
   * design's `err()` (create-form.js:263-268). Only the Create Contact drawer passes it (CQ1).
   */
  errors?: Record<string, string>;
}) {
  const fillable = defs.filter((def) => !def.calculated);
  if (fillable.length === 0) return null;
  return (
    <>
      {designLabels ? null : (
        <p className="crm-fs-8 crm-text-muted" style={{ margin: '8px 0 0' }}>
          Custom fields
        </p>
      )}
      {fillable.map((def) => {
        const error = errors?.[`custom.${def.name}`];
        const errorId = error ? `${idPrefix}-${def.name}-error` : undefined;
        return (
          <div key={def.id} className={error ? 'field is-invalid' : 'field'}>
            <label htmlFor={`${idPrefix}-${def.name}`} title={def.description || undefined}>
              {designLabels ? (
                <>
                  {def.label}
                  {def.required ? (
                    <span className="cf-req" aria-hidden>
                      *
                    </span>
                  ) : null}
                </>
              ) : def.required ? (
                `${def.label} *`
              ) : (
                def.label
              )}
            </label>
            <CustomFieldInput
              def={def}
              id={`${idPrefix}-${def.name}`}
              value={values[def.name] ?? (def.type === 'multiselect' ? [] : '')}
              onChange={(value) => onChange(def.name, value)}
              designSelect={designSelects}
              invalidId={errorId}
            />
            {error ? (
              <span className="field__error" id={errorId} role="alert">
                {error}
              </span>
            ) : null}
          </div>
        );
      })}
      {defs.some((d) => d.type === 'datetime') ? (
        <p className="crm-fs-8 crm-text-muted">Times are in {timeZone}.</p>
      ) : null}
    </>
  );
}

const optionLabel = (def: CustomPropertyDefinition, value: string) =>
  def.options?.find((o) => o.value === value)?.label ?? value;

/** A stored value as text for the About section. */
export function formatCustomValue(
  def: CustomPropertyDefinition,
  value: StoredValue | undefined,
  /** For currency fields (HUB-252); without it the number shows as is. */
  currencyCode?: string,
  /**
   * Writes date and date-time fields in the user's format and time zone (`formatUserDate`, as
   * the timeline; a date has no time and stays on its day); without it, in the browser's.
   */
  formatDateTime?: (iso: string) => string,
) {
  if (value === undefined || value === null || value === '') return '--';
  if (Array.isArray(value)) {
    return value.length ? value.map((v) => optionLabel(def, String(v))).join(', ') : '--';
  }
  switch (def.type) {
    case 'number': {
      // HUB-252: currency and percent fields show as such.
      const control = displayControl(def);
      if (control === 'percent') {
        const n = Number(value);
        return Number.isFinite(n) ? formatPercent(n) : `${value}%`;
      }
      if (control === 'currency' && currencyCode) {
        const n = Number(value);
        if (Number.isFinite(n)) {
          try {
            return new Intl.NumberFormat(undefined, {
              style: 'currency',
              currency: currencyCode,
            }).format(n);
          } catch {
            return String(value);
          }
        }
      }
      return String(value);
    }
    case 'boolean':
      return value === true ? 'Yes' : value === false ? 'No' : String(value);
    case 'select':
      return optionLabel(def, String(value));
    case 'date': {
      const [y, m, d] = String(value).split('-').map(Number);
      if (!y || !m || !d) return String(value);
      if (formatDateTime) return formatDateTime(String(value));
      return new Date(y, m - 1, d).toLocaleDateString(undefined, { dateStyle: 'medium' });
    }
    case 'datetime': {
      const date = new Date(String(value));
      if (Number.isNaN(date.getTime())) return String(value);
      if (formatDateTime) return formatDateTime(String(value));
      return date.toLocaleString(undefined, { dateStyle: 'medium', timeStyle: 'short' });
    }
    default:
      return String(value);
  }
}

/**
 * One input per field type and display control (HUB-252): radio buttons, checkboxes, phone,
 * email and URL inputs, currency and percent numbers. Read-only fields are shown locked.
 * Archived options stay listed only when already chosen.
 */
export function CustomFieldInput({
  def,
  id,
  value,
  onChange,
  designSelect = false,
  invalidId,
}: {
  def: CustomPropertyDefinition;
  id: string;
  value: CustomUiValue;
  onChange: (value: CustomUiValue) => void;
  /** A single-choice field as the 28 Oct design's dropdown, even when set to Radio select. */
  designSelect?: boolean;
  /**
   * The id of this field's error line: marks the control invalid and points to it, as the
   * design's `err()` (create-form.js:267). Only Contacts' create and edit pass it (CQ1).
   */
  invalidId?: string;
}) {
  const aria = invalidId ? { 'aria-invalid': true, 'aria-describedby': invalidId } : {};
  const control = displayControl(def);
  const currencyCode = useBusinessCurrency(control === 'currency');
  // DMG9: a multiple users field picks users, as Multiple checkboxes picks options.
  if (isMultiUserField(def)) {
    return <CrmUsersInput def={def} id={id} value={value} onChange={onChange} aria={aria} />;
  }
  const text = Array.isArray(value) ? '' : value;
  // A locked (read-only) input can't be filled in, so it never blocks the form as required.
  const required = def.required && def.type !== 'multiselect' && !isLockedField(def);
  // Only imports, the migration and calculations change a read-only field.
  const disabled = isLockedField(def);
  const lockedTitle = lockedFieldTitle(def);
  const options = fieldChoices(def, Array.isArray(value) ? value : [value]);

  switch (def.type) {
    case 'textarea':
      return (
        <textarea
          className="input"
          id={id}
          {...aria}
          rows={3}
          style={TEXTAREA_STYLE}
          required={required}
          disabled={disabled}
          title={lockedTitle}
          value={text}
          onChange={(e) => onChange(e.target.value)}
        />
      );
    case 'number': {
      const input = (
        <input
          className="input"
          id={id}
          {...aria}
          type="number"
          step="any"
          required={required}
          disabled={disabled}
          title={lockedTitle}
          value={text}
          onChange={(e) => onChange(e.target.value)}
        />
      );
      if (control === 'currency') {
        return (
          <span className="input-affix input-affix--prefix">
            <span className="input-affix__text" aria-hidden>
              {currencySymbol(currencyCode)}
            </span>
            {input}
          </span>
        );
      }
      if (control === 'percent') {
        return (
          <span className="input-affix input-affix--suffix">
            {input}
            <span className="input-affix__text" aria-hidden>
              %
            </span>
          </span>
        );
      }
      return input;
    }
    case 'date':
      return (
        <input
          className="input"
          id={id}
          {...aria}
          type="date"
          required={required}
          disabled={disabled}
          title={lockedTitle}
          value={text}
          onChange={(e) => onChange(e.target.value)}
        />
      );
    case 'datetime':
      return (
        <input
          className="input"
          id={id}
          {...aria}
          type="datetime-local"
          required={required}
          disabled={disabled}
          title={lockedTitle}
          value={text}
          onChange={(e) => onChange(e.target.value)}
        />
      );
    case 'boolean':
      return (
        <select
          className="input"
          id={id}
          {...aria}
          required={required}
          disabled={disabled}
          title={lockedTitle}
          value={text}
          onChange={(e) => onChange(e.target.value)}
        >
          <option value="">--</option>
          <option value="true">Yes</option>
          <option value="false">No</option>
        </select>
      );
    case 'select':
      if (control === 'radio' && !designSelect) {
        return (
          <div
            className="prp-radios"
            id={id}
            {...aria}
            role="radiogroup"
            aria-required={required || undefined}
            title={lockedTitle}
          >
            {options.map((o) => (
              <label key={o.value} className="prp-radio">
                <input
                  type="radio"
                  name={id}
                  value={o.value}
                  required={required}
                  disabled={disabled}
                  checked={text === o.value}
                  onChange={() => onChange(o.value)}
                />
                <span>{o.label}</span>
              </label>
            ))}
            {!required && !disabled && text ? (
              <button
                type="button"
                className="link"
                style={{ justifySelf: 'start' }}
                onClick={() => onChange('')}
              >
                Clear
              </button>
            ) : null}
          </div>
        );
      }
      return (
        <select
          className={designSelect ? 'input cf-select' : 'input'}
          id={id}
          {...aria}
          required={required}
          disabled={disabled}
          title={lockedTitle}
          value={text}
          onChange={(e) => onChange(e.target.value)}
        >
          {/* The design's empty choice reads "Select", blank when locked (create-form.js:145). */}
          <option value="">{designSelect ? (disabled ? '' : 'Select') : '--'}</option>
          {options.map((o) => (
            <option key={o.value} value={o.value}>
              {o.label}
            </option>
          ))}
        </select>
      );
    case 'multiselect': {
      // HubSpot's "Multiple checkboxes": one checkbox per option.
      const picked = Array.isArray(value) ? value : [];
      return (
        <div className="prp-radios" id={id} {...aria} role="group" title={lockedTitle}>
          {options.map((o) => (
            <label key={o.value} className="prp-radio">
              <input
                type="checkbox"
                value={o.value}
                disabled={disabled}
                checked={picked.includes(o.value)}
                onChange={(e) =>
                  onChange(
                    e.target.checked
                      ? options
                          .map((x) => x.value)
                          .filter((v) => v === o.value || picked.includes(v))
                      : picked.filter((v) => v !== o.value),
                  )
                }
              />
              <span>{o.label}</span>
            </label>
          ))}
        </div>
      );
    }
    default:
      return (
        <input
          className="input"
          id={id}
          {...aria}
          type={
            control === 'phonenumber'
              ? 'tel'
              : control === 'email'
                ? 'email'
                : control === 'url'
                  ? 'url'
                  : 'text'
          }
          required={required}
          disabled={disabled}
          title={lockedTitle}
          value={text}
          onChange={(e) => onChange(e.target.value)}
        />
      );
  }
}

/**
 * DMG9: a multiple users field's checkboxes, one per active user (and the users it holds), in
 * the Multiple checkboxes layout.
 */
function CrmUsersInput({
  def,
  id,
  value,
  onChange,
  aria,
}: {
  def: CustomPropertyDefinition;
  id: string;
  value: CustomUiValue;
  onChange: (value: CustomUiValue) => void;
  aria: Record<string, unknown>;
}) {
  const { owners } = useOwners(true, true);
  // Only users of the field's teams, plus those the record already holds.
  const teams = useTeamOptions(hasTeamLimit([def]));
  const picked = ownerIdsOf(value);
  const options = crmUserChoices(owners, picked, def, teams);
  const disabled = isLockedField(def);
  return (
    <div className="prp-radios" id={id} {...aria} role="group" title={lockedFieldTitle(def)}>
      {options.map((o) => (
        <label key={o.value} className="prp-radio">
          <input
            type="checkbox"
            value={o.value}
            disabled={disabled}
            checked={picked.includes(o.value)}
            onChange={(e) =>
              onChange(
                e.target.checked
                  ? options.map((x) => x.value).filter((v) => v === o.value || picked.includes(v))
                  : picked.filter((v) => v !== o.value),
              )
            }
          />
          <span>{o.label}</span>
        </label>
      ))}
    </div>
  );
}

/** Fields edited with the in-place dropdown (HUB-615): selects, Yes/No and multi-selects. */
function isChoiceField(def: CustomPropertyDefinition): boolean {
  return (
    def.type === 'select' ||
    def.type === 'boolean' ||
    def.type === 'multiselect' ||
    // DMG9: a multiple users field.
    isMultiUserField(def)
  );
}

/** A choice field's options; archived ones and HubSpot-filled values only when chosen. */
function choiceOptions(
  def: CustomPropertyDefinition,
  value: CustomUiValue,
  owners: Owner[] = [],
  teams: TeamOption[] | null = null,
): Array<{ value: string; label: string }> {
  if (isMultiUserField(def)) return crmUserChoices(owners, ownerIdsOf(value), def, teams);
  if (def.type === 'boolean') {
    return [
      { value: 'true', label: 'Yes' },
      { value: 'false', label: 'No' },
    ];
  }
  return fieldChoices(def, Array.isArray(value) ? value : [value]).map((o) => ({
    value: o.value,
    label: o.label,
  }));
}

/** How the About card saves one custom field in place (HUB-615). */
export interface CustomFieldsEdit {
  canEdit: boolean;
  /** Why the record can't be edited, shown on hover. */
  lockedTitle?: string;
  timeZone: string;
  /** Date-time values as the record writes them (`formatCustomValue`); else the browser's. */
  formatDateTime?: (iso: string) => string;
  /** PATCH `customProperties: { [name]: value }` (`null` clears) and update the record. */
  onSave: (name: string, value: StoredValue | null) => Promise<void>;
}

/**
 * Label / value rows of the custom fields, styled like the other About fields. With `edit`,
 * each value is edited in place; read-only fields only show their value.
 */
export function CustomFieldsList({
  defs,
  values,
  logicObjectType,
  edit,
  onHistory,
}: {
  defs: CustomPropertyDefinition[];
  values: CustomProperties;
  /** HUB-355: apply this object's conditional property logic (hide unmet dependents). */
  logicObjectType?: string;
  edit?: CustomFieldsEdit;
  /** HUB-356: open a field's property history (gets the field's name). */
  onHistory?: (name: string) => void;
}) {
  const rules = usePropertyLogic(logicObjectType);
  const look = useDesignPropertyRow();
  // DMG9: names of the users a multiple users field holds, and its picker's choices.
  const { owners } = useOwners(defs.some(isMultiUserField), true);
  const teams = useTeamOptions(hasTeamLimit(defs.filter(isMultiUserField)));
  const shown = applyPropertyLogic(defs, rules, values);
  if (shown.length === 0) return null;
  const textOf = (def: CustomPropertyDefinition, formatDateTime?: (iso: string) => string) =>
    isMultiUserField(def)
      ? crmUserText(values[def.name], owners)
      : formatCustomValue(def, values[def.name], undefined, formatDateTime);
  return (
    <>
      {shown.map((def) => {
        const value = edit ? (
          <InlineEdit<CustomUiValue>
            label={def.label}
            saveOn={def.type === 'boolean' || def.type === 'select' ? 'change' : 'blur'}
            dropdown={isChoiceField(def)}
            display={textOf(def, edit.formatDateTime)}
            canEdit={edit.canEdit && !isLockedField(def)}
            lockedTitle={lockedFieldTitle(def) ?? edit.lockedTitle}
            initial={() => toUiValue(def, values[def.name], edit.timeZone)}
            renderInput={({ id, value, onChange }) =>
              isChoiceField(def) ? (
                <InlineDropdown
                  id={id}
                  value={value}
                  onChange={onChange}
                  options={choiceOptions(def, value, owners, teams)}
                  emptyLabel={
                    def.type === 'multiselect' || isMultiUserField(def) ? undefined : '--'
                  }
                  multiple={def.type === 'multiselect' || isMultiUserField(def)}
                />
              ) : (
                <CustomFieldInput
                  def={{ ...def, required: false }}
                  id={id}
                  value={value}
                  onChange={onChange}
                />
              )
            }
            onSave={async (ui) => {
              if (sameUiValue(ui, toUiValue(def, values[def.name], edit.timeZone))) return;
              const parsed = fromUiValue(def, ui, edit.timeZone);
              if ('error' in parsed) throw new Error(parsed.error);
              if (parsed.value === null && def.required) {
                throw new Error(`${def.label} is required`);
              }
              await edit.onSave(def.name, parsed.value);
            }}
          />
        ) : (
          textOf(def)
        );
        // R3: inside "View all properties", the design's row around the same value or editor.
        if (look) {
          return (
            <DesignPropertyRow key={def.id} look={look}>
              {value}
            </DesignPropertyRow>
          );
        }
        return (
          <div key={def.id} className="crm-about-field">
            <div className="crm-about-label" title={def.description || undefined}>
              {def.label}
              {onHistory ? (
                <PropertyHistoryButton label={def.label} onClick={() => onHistory(def.name)} />
              ) : null}
            </div>
            <div className="crm-about-value">{value}</div>
          </div>
        );
      })}
    </>
  );
}
