'use client';

import { useState } from 'react';
import { flushSync } from 'react-dom';
import { Field, FormDrawer } from '@/components/crm/FormDrawer';
import { useToast } from '@/components/crm/ToastProvider';
import { contactsWithEmail, updateContact } from '@/features/contacts/api.client';
import type { Contact, ContactWrite, UpdateContactBody } from '@/features/contacts/types';
import type { CustomPropertyDefinition } from '@/features/custom-properties/api.client';
import {
  applyPropertyLogic,
  propertyLogicValues,
  usePropertyLogic,
} from '@/features/custom-properties/logic';
import type { PicklistOption } from '@/features/picklists/api.client';
import {
  CustomFieldInput,
  fromUiValue,
  sameUiValue,
  toUiValue,
  type CustomUiValue,
} from './custom-fields';
import { sanitizePhoneInput } from '@/lib/validation/contact-company';
import { ownerDisplayName, ownerRecordLabel } from '@/features/owners/labels';
import { useOwners } from '@/features/owners/useOwners';
import { useFieldAccess, VIEW_ONLY_TITLE } from '@/features/permission-sets/field-access';
import {
  duplicateEmailText,
  duplicateWarningText,
  editContactProblems,
  emailInUse,
  editErrorProps,
  editOnForm,
} from './editContactErrors';
import {
  contactErrorText,
  contactFieldLabel,
  focusFirstInvalid,
  placeFieldErrors,
} from './fieldErrors';
import { useOpenCount } from './shared';

type TextField = 'firstName' | 'lastName' | 'email' | 'phone' | 'companyName' | 'jobTitle';
/**
 * The text inputs, in order; `max` is the most characters the browser lets one take. D-18: the
 * names, Company name and Job title have none, so the API's limit shows under the field as
 * "<Label> can be at most N characters." (CQ1) instead of the text being cut off.
 */
export const TEXT_FIELDS: { name: TextField; label: string; type?: string; max?: number }[] = [
  { name: 'firstName', label: 'First name' },
  { name: 'lastName', label: 'Last name' },
  { name: 'email', label: 'Email', type: 'email', max: 191 },
  { name: 'phone', label: 'Phone number', type: 'tel', max: 50 },
  { name: 'companyName', label: 'Company name' },
  { name: 'jobTitle', label: 'Job title' },
];

/** The selects' ids, for focus on the first invalid field; the others are `edit-<name>`. */
const EDIT_INPUT_IDS: Record<string, string> = {
  ownerId: 'edit-owner',
  lifecycleStage: 'edit-lifecycle',
  leadStatus: 'edit-lead-status',
};

/** Active options, plus the record's current value when it was archived (so it isn't lost). */
function picklistChoices(options: PicklistOption[], current: string | null) {
  const list = options.map((o) => ({ value: o.value, label: o.label }));
  if (current && !list.some((o) => o.value === current)) {
    list.push({ value: current, label: current });
  }
  return list;
}

/**
 * Edit a contact (PATCH /contacts/:id): only changed fields are sent, with the `updatedAt`
 * loaded, so a change by someone else meanwhile is a 409. Custom fields per their type.
 */
export function EditContactDrawer({
  open,
  onClose,
  contact,
  lifecycleStages,
  leadStatuses,
  customDefs,
  timeZone,
  onSaved,
}: {
  open: boolean;
  onClose: () => void;
  contact: Contact;
  lifecycleStages: PicklistOption[];
  leadStatuses: PicklistOption[];
  customDefs: CustomPropertyDefinition[];
  timeZone: string;
  onSaved: (contact: ContactWrite) => void;
}) {
  const toast = useToast();
  // HUB-317: hidden built-in fields aren't shown, view-only ones are locked; neither is sent.
  const access = useFieldAccess('contact');
  const { owners: ownerRows, error: ownersError } = useOwners(open, true);
  /** The loaded value of a custom field, as its input shows it. */
  const loadedCustom = (def: CustomPropertyDefinition) =>
    toUiValue(def, contact.customProperties[def.name], timeZone);
  /** Only the custom fields changed in this opening of the drawer. */
  const [custom, setCustom] = useState<Record<string, CustomUiValue>>({});
  /** CQ1 #13: each check's message under its field (keys: name, `custom.<name>`). */
  const [errors, setErrors] = useState<Record<string, string>>({});
  /** Lifecycle stage and lead status as chosen so far: field rules can depend on them. */
  const [stages, setStages] = useState<{ lifecycleStage?: string; leadStatus?: string }>({});
  const openCount = useOpenCount(open, () => {
    setCustom({});
    setStages({});
    setErrors({});
  });
  // HUB-355: conditional property logic, on the values as edited so far.
  const propertyLogic = usePropertyLogic('contact');
  const shownDefs = applyPropertyLogic(
    customDefs,
    propertyLogic,
    propertyLogicValues(
      'contact',
      {
        lifecycleStage: stages.lifecycleStage ?? contact.lifecycleStage,
        leadStatus: stages.leadStatus ?? contact.leadStatus,
      },
      Object.fromEntries(customDefs.map((d) => [d.name, custom[d.name] ?? loadedCustom(d)])),
    ),
  );

  // Assign picker: active only; keep current deactivated owner so the select can show it.
  const owners = ownerRows
    .filter((o) => o.active || o.userId === contact.owner?.id)
    .map((o) => ({
      id: o.userId,
      name: o.active ? o.name : ownerDisplayName(o),
    }));
  if (contact.owner && !owners.some((o) => o.id === contact.owner?.id)) {
    owners.push({
      id: contact.owner.id,
      name: ownerRecordLabel({
        name: contact.owner.name,
        isActive: contact.owner.isActive,
      }),
    });
  }
  const showOwner = !ownersError && ownerRows.length > 0;

  const showErrors = (found: Record<string, string>) => {
    setErrors(found);
    // As the design's create form (create-form.js:279): the first invalid field, in form order,
    // gets focus.
    const ids = new Set(
      Object.keys(found).map(
        (key) => EDIT_INPUT_IDS[key] ?? `edit-${key.replace(/^custom\./, 'custom-')}`,
      ),
    );
    window.setTimeout(() => focusFirstInvalid(document.getElementById('contactEditModal'), ids));
  };
  const clearError = (key: string) =>
    setErrors((cur) => {
      if (!(key in cur)) return cur;
      const rest = { ...cur };
      delete rest[key];
      return rest;
    });

  /**
   * FormDrawer sets `is-invalid` on required fields straight on the DOM, after `validate` and
   * before `onSubmit` (FormDrawer.tsx:144-156), and may stop there. Render without errors first,
   * so no message is hidden while its state stays set, and the class React puts back is the one
   * shown, even for the same error twice.
   */
  const clearBeforeSubmit = () => {
    flushSync(() => setErrors({}));
    return true;
  };

  const onSubmit = async (d: Record<string, string>) => {
    const changed = (name: TextField) =>
      ((d[name] ?? '').trim() || null) !== (contact[name] ?? null);
    const found = editContactProblems({
      values: d,
      contact,
      locked: access.locked,
      customDefs: shownDefs,
      custom,
      loaded: loadedCustom,
      timeZone,
    });
    if (!access.locked('email') && changed('email') && !found.email) {
      // Sheet #147: the email must stay unique, as on create.
      const taken = await contactsWithEmail((d.email ?? '').trim(), contact.id).catch(() => ({
        matches: [],
        hidden: 0,
      }));
      if (emailInUse(taken)) found.email = duplicateEmailText(taken.matches, taken.hidden);
    }
    if (Object.keys(found).length) {
      showErrors(found);
      return false;
    }
    const phoneRaw = sanitizePhoneInput(d.phone ?? '');

    const body: UpdateContactBody = {};
    for (const f of TEXT_FIELDS) {
      if (access.locked(f.name) || !changed(f.name)) continue;
      body[f.name] = f.name === 'phone' ? phoneRaw || null : (d[f.name] ?? '').trim() || null;
    }
    if (showOwner && !access.locked('ownerId')) {
      const ownerId = d.ownerId || null;
      if (ownerId !== (contact.owner?.id ?? null)) body.ownerId = ownerId;
    }
    for (const field of ['lifecycleStage', 'leadStatus'] as const) {
      if (access.locked(field)) continue;
      const next = d[field] || null;
      if (next !== (contact[field] ?? null)) body[field] = next;
    }

    const customBody: NonNullable<UpdateContactBody['customProperties']> = {};
    // Hidden fields are left as they are.
    for (const def of shownDefs) {
      const ui = custom[def.name];
      if (ui === undefined || sameUiValue(ui, loadedCustom(def))) continue;
      // Checked above (editContactProblems), so only a valid value is left here.
      const result = fromUiValue(def, ui, timeZone);
      if ('error' in result) return false;
      customBody[def.name] = result.value;
    }
    if (Object.keys(customBody).length) body.customProperties = customBody;

    if (Object.keys(body).length === 0) {
      toast('Nothing changed', 'info');
      return;
    }
    const labelOf = (key: string) => contactFieldLabel(key, customDefs);
    try {
      const saved = await updateContact(contact.id, { ...body, updatedAt: contact.updatedAt });
      onSaved(saved);
      const dupText = duplicateWarningText(
        saved.warnings?.find((w) => w.code === 'duplicate_email'),
      );
      if (dupText) {
        toast(dupText, 'info', { durationMs: 8000 });
      } else {
        toast('Contact saved');
      }
    } catch (err) {
      // The API's field details under their fields; the rest (a stale save, 403, the network)
      // in the toast, in words.
      const placed = placeFieldErrors(err, {
        onForm: editOnForm(access, shownDefs, showOwner),
        labelOf,
      });
      if (placed && Object.keys(placed.fields).length) showErrors(placed.fields);
      const rest = placed ? placed.form : contactErrorText(err, labelOf);
      if (rest) toast(rest, 'danger', { durationMs: 8000 });
      return false;
    }
  };

  return (
    <FormDrawer
      id="contactEditModal"
      title="Edit contact"
      size="wide"
      submitLabel="Save"
      open={open}
      onClose={onClose}
      validate={clearBeforeSubmit}
      onSubmit={onSubmit}
    >
      <div className="form-grid" key={openCount}>
        {TEXT_FIELDS.filter((f) => !access.hidden(f.name)).map((f) => {
          const shown = editErrorProps(
            errors,
            f.name,
            f.name === 'jobTitle' || f.name === 'companyName' ? 'span-2' : undefined,
          );
          return (
            <Field key={f.name} label={f.label} htmlFor={`edit-${f.name}`} {...shown.field}>
              <input
                className="input"
                id={`edit-${f.name}`}
                name={f.name}
                type={f.type ?? 'text'}
                maxLength={f.max}
                inputMode={f.name === 'phone' ? 'tel' : undefined}
                defaultValue={contact[f.name] ?? ''}
                disabled={access.locked(f.name)}
                title={access.locked(f.name) ? VIEW_ONLY_TITLE : undefined}
                onInput={() => clearError(f.name)}
                {...shown.input}
              />
            </Field>
          );
        })}
        {showOwner ? (
          <Field
            label="Contact owner"
            htmlFor="edit-owner"
            {...editErrorProps(errors, 'ownerId', 'span-2').field}
          >
            <select
              className="input"
              id="edit-owner"
              {...editErrorProps(errors, 'ownerId').input}
              onChange={() => clearError('ownerId')}
              name="ownerId"
              defaultValue={contact.owner?.id ?? ''}
              disabled={access.locked('ownerId')}
              title={access.locked('ownerId') ? VIEW_ONLY_TITLE : undefined}
            >
              <option value="">Unassigned</option>
              {owners.map((o) => (
                <option key={o.id} value={o.id}>
                  {o.name}
                </option>
              ))}
            </select>
          </Field>
        ) : null}
        {access.hidden('lifecycleStage') ? null : (
          <Field
            label="Lifecycle stage"
            htmlFor="edit-lifecycle"
            {...editErrorProps(errors, 'lifecycleStage').field}
          >
            <select
              className="input"
              id="edit-lifecycle"
              {...editErrorProps(errors, 'lifecycleStage').input}
              onChange={(e) => {
                clearError('lifecycleStage');
                const lifecycleStage = e.target.value;
                setStages((st) => ({ ...st, lifecycleStage }));
              }}
              name="lifecycleStage"
              defaultValue={contact.lifecycleStage ?? ''}
              disabled={access.locked('lifecycleStage')}
            >
              <option value="">--</option>
              {picklistChoices(lifecycleStages, contact.lifecycleStage).map((o) => (
                <option key={o.value} value={o.value}>
                  {o.label}
                </option>
              ))}
            </select>
          </Field>
        )}
        {access.hidden('leadStatus') ? null : (
          <Field
            label="Lead status"
            htmlFor="edit-lead-status"
            {...editErrorProps(errors, 'leadStatus').field}
          >
            <select
              className="input"
              id="edit-lead-status"
              {...editErrorProps(errors, 'leadStatus').input}
              onChange={(e) => {
                clearError('leadStatus');
                const leadStatus = e.target.value;
                setStages((st) => ({ ...st, leadStatus }));
              }}
              name="leadStatus"
              defaultValue={contact.leadStatus ?? ''}
              disabled={access.locked('leadStatus')}
            >
              <option value="">--</option>
              {picklistChoices(leadStatuses, contact.leadStatus).map((o) => (
                <option key={o.value} value={o.value}>
                  {o.label}
                </option>
              ))}
            </select>
          </Field>
        )}

        {customDefs.length ? (
          <p className="span-2 crm-fs-8 crm-text-muted" style={{ margin: '8px 0 0' }}>
            Custom fields
          </p>
        ) : null}
        {shownDefs.map((def) => {
          const key = `custom.${def.name}`;
          const shown = editErrorProps(
            errors,
            key,
            def.type === 'textarea' || def.type === 'multiselect' ? 'span-2' : undefined,
          );
          return (
            <Field
              key={def.id}
              label={def.required ? `${def.label} *` : def.label}
              htmlFor={`edit-custom-${def.name}`}
              title={def.description || undefined}
              {...shown.field}
            >
              <CustomFieldInput
                def={def}
                id={`edit-custom-${def.name}`}
                value={custom[def.name] ?? loadedCustom(def)}
                onChange={(value) => {
                  setCustom((cur) => ({ ...cur, [def.name]: value }));
                  clearError(key);
                }}
                invalidId={shown.field.errorId}
              />
            </Field>
          );
        })}
      </div>
      {customDefs.some((d) => d.type === 'datetime') ? (
        <p className="crm-fs-8 crm-text-muted crm-mt-3">Times are in {timeZone}.</p>
      ) : null}
    </FormDrawer>
  );
}
