'use client';

import { useSearchParams } from 'next/navigation';
import { Suspense, useMemo } from 'react';
import { useToast } from '@/components/crm/ToastProvider';
import {
  getCreateForm,
  saveCreateForm,
  standardLabels,
  type CreateFormField,
} from '@/features/create-forms/api.client';
import {
  listCustomProperties,
  type CustomPropertyDefinition,
} from '@/features/custom-properties/api.client';
import { defaultFormKey, usableDefaultForm } from '@/features/create-forms/defaults';
import { offeredInFormEditor } from '@/features/custom-properties/show-in-forms';
import { listPropertyGroups, type PropertyGroup } from '@/features/data-model/api.client';
import { listObjectDefinitions } from '@/features/objects/api.client';
import { listAllOwners } from '@/features/owners/api.client';
import { listPicklistOptions, type PicklistOption } from '@/features/picklists/api.client';
import { errorText } from '@/lib/api/errors';
import { DesignFrame, type DesignLive } from './DesignFrame';
import { formHeadings } from './form-headings';

/** The design's object keys and names for the built-in objects. */
const BUILT_IN: Record<string, { design: string; single: string; plural: string; list: string }> = {
  contact: { design: 'contacts', single: 'Contact', plural: 'Contacts', list: '/contacts' },
  company: { design: 'companies', single: 'Company', plural: 'Companies', list: '/companies' },
  deal: { design: 'deals', single: 'Deal', plural: 'Deals', list: '/deals' },
};

/** The design's field types (what the canvas draws) for the standard create fields. */
const STANDARD_TYPE: Record<string, string> = {
  email: 'Email',
  phone: 'Phone number',
  ownerId: 'CRM user',
  lifecycleStage: 'Radio select',
  leadStatus: 'Radio select',
  industry: 'Dropdown select',
  domain: 'URL',
  website: 'URL',
  pipelineId: 'Dropdown select',
  stageId: 'Radio select',
  amount: 'Number',
  closeDate: 'Date picker',
  dealType: 'Radio select',
  priority: 'Dropdown select',
  company: 'Dropdown select',
  contact: 'Dropdown select',
};
const CUSTOM_TYPE: Record<string, string> = {
  text: 'Single-line text',
  textarea: 'Multi-line text',
  number: 'Number',
  date: 'Date picker',
  datetime: 'Date picker',
  select: 'Dropdown select',
  multiselect: 'Multiple checkboxes',
  boolean: 'Single checkbox',
};
/** Fields that are always on the form and always required (the API adds them back anyway). */
const LOCKED: Record<string, string[]> = {
  deal: ['name', 'pipelineId', 'stageId'],
  custom: ['displayName'],
};
/** "One of these must be required" (the design's rule), per object. */
const ONE_OF: Record<string, { keys: string[]; text: string }> = {
  contact: {
    keys: ['email', 'firstName', 'lastName'],
    text: 'Either the email address, first name, or last name must be required.',
  },
  company: {
    keys: ['name', 'domain'],
    text: 'Either the company name or company domain name must be required.',
  },
  deal: { keys: ['name'], text: 'Deal name, pipeline and deal stage are always required.' },
};

const STANDARD_FIELDS: Record<string, string[]> = {
  contact: [
    'email',
    'firstName',
    'lastName',
    'companyName',
    'jobTitle',
    'phone',
    'ownerId',
    'lifecycleStage',
    'leadStatus',
  ],
  company: [
    'name',
    'domain',
    'ownerId',
    'industry',
    'phone',
    'city',
    'state',
    'country',
    'website',
  ],
  deal: [
    'name',
    'pipelineId',
    'stageId',
    'amount',
    'closeDate',
    'ownerId',
    'dealType',
    'priority',
    'company',
    'contact',
  ],
  custom: ['displayName', 'pipelineId', 'stageId', 'ownerId'],
};

/** Conditional logic and associations have no API yet: they stay in this browser. */
const extrasKey = (objectType: string) => `crm.create-form-extras.${objectType}`;
function readExtras(objectType: string): { logic: unknown[]; assoc: unknown[] } | null {
  try {
    const raw = window.localStorage.getItem(extrasKey(objectType));
    return raw ? (JSON.parse(raw) as { logic: unknown[]; assoc: unknown[] }) : null;
  } catch {
    return null;
  }
}
function writeExtras(objectType: string, value: { logic: unknown[]; assoc: unknown[] }) {
  try {
    window.localStorage.setItem(extrasKey(objectType), JSON.stringify(value));
  } catch {
    // Storage off: the logic lasts for this page only.
  }
}

type DesignField = { key: string; label: string; type: string; req: boolean; lock: boolean };

/**
 * "Edit <Object> form" (design form-editor.php) on the create forms API (HUB-593): the
 * properties on the 'Create <object>' form, their order and which are required. Conditional
 * logic and associations are kept in this browser until the API stores them.
 */
function FormEditor() {
  const params = useSearchParams();
  const toast = useToast();
  const objectType = params.get('object') ?? 'contact';
  const from = params.get('from');

  const live = useMemo<DesignLive>(() => {
    const kind = BUILT_IN[objectType] ? objectType : 'custom';
    const lockSet = new Set(LOCKED[kind] ?? []);
    return {
      selector: '[data-fe-config]',
      load: async () => {
        let meta = BUILT_IN[objectType];
        if (!meta) {
          const def = (await listObjectDefinitions()).find((d) => d.key === objectType);
          meta = {
            design: 'events',
            single: def?.singularLabel ?? objectType,
            plural: def?.pluralLabel ?? objectType,
            list: `/objects/${objectType}`,
          };
        }
        const picklistType =
          objectType === 'contact' || objectType === 'company' || objectType === 'deal'
            ? objectType
            : null;
        const [form, defs, fieldGroups, owners, picklists] = await Promise.all([
          getCreateForm(objectType),
          listCustomProperties({ objectType }).catch(() => [] as CustomPropertyDefinition[]),
          listPropertyGroups({ objectType }).catch((err: unknown) => {
            console.warn('Property groups failed to load', err);
            toast(
              "Property groups couldn't be loaded, so properties are listed under their groups' internal names. Reload the page to try again.",
              'info',
              { durationMs: 8000 },
            );
            return [] as PropertyGroup[];
          }),
          listAllOwners(false).catch(() => []),
          picklistType
            ? listPicklistOptions({ objectType: picklistType }).catch(() => [] as PicklistOption[])
            : Promise.resolve([] as PicklistOption[]),
        ]);
        const choices: Record<string, string[]> = {};
        for (const option of picklists) {
          if (option.archived) continue;
          (choices[option.field] ??= []).push(option.label);
        }
        const labels = standardLabels(objectType);
        const active = defs
          .filter((d) => !d.archived && !d.readOnly && !d.calculated)
          .sort((a, b) => a.displayOrder - b.displayOrder);
        const labelOf = (field: string) =>
          labels[field] ??
          active.find((d) => `custom.${d.name}` === field)?.label ??
          field.replace(/^custom\./, '');
        const typeOf = (field: string) => {
          const def = active.find((d) => `custom.${d.name}` === field);
          return def
            ? (CUSTOM_TYPE[def.type] ?? 'Single-line text')
            : (STANDARD_TYPE[field] ?? 'Single-line text');
        };
        const toDesign = (f: CreateFormField): DesignField => ({
          key: f.field,
          label: labelOf(f.field),
          type: typeOf(f.field),
          req: f.required || lockSet.has(f.field),
          lock: lockSet.has(f.field),
        });
        const groups = new Map<string, Array<{ key: string; label: string; type: string }>>();
        const { info, headingOf } = formHeadings(fieldGroups, {
          key: objectType,
          singular: meta.single,
        });
        groups.set(
          info,
          (STANDARD_FIELDS[kind] ?? []).map((field) => ({
            key: field,
            label: labelOf(field),
            type: typeOf(field),
          })),
        );
        // Fields hidden from forms ("Show property in forms" off) aren't offered, unless required.
        // One already on the form keeps its label (labelOf reads every active field) and can
        // still be removed there.
        for (const d of active) {
          if (
            (d.type === 'select' || d.type === 'multiselect') &&
            d.options?.some((o) => !o.archived)
          ) {
            choices[`custom.${d.name}`] = d.options.filter((o) => !o.archived).map((o) => o.label);
          }
        }
        for (const d of active.filter(offeredInFormEditor)) {
          const group = headingOf(d.groupName);
          groups.set(group, [
            ...(groups.get(group) ?? []),
            { key: `custom.${d.name}`, label: d.label, type: typeOf(`custom.${d.name}`) },
          ]);
        }
        const extras = readExtras(objectType);
        const current = {
          fields: form.fields.map(toDesign),
          logic: extras?.logic ?? [],
          assoc: extras?.assoc ?? null,
        };
        return {
          value: {
            object: meta.design,
            meta: { single: meta.single, plural: meta.plural, list: meta.list },
            back: from && from.startsWith('/') ? from : `/settings/objects?object=${objectType}`,
            groups: [...groups].map(([name, props]) => ({ name, props })),
          },
          forms: {
            current,
            defaults: {
              // The API's default as this business can use it (B3: the company form's HubSpot
              // fields only where they exist), so Reset then Save never stores a missing field.
              fields: usableDefaultForm(defaultFormKey(objectType), defs).map(toDesign),
              logic: [],
              assoc: current.assoc,
            },
            oneOf: ONE_OF[kind] ?? {
              keys: ['displayName'],
              text: `${meta.single} name is always required.`,
            },
            preview: {
              owners: owners.filter((o) => o.active).map((o) => o.name),
              choices,
            },
          },
        };
      },
      onAction: async (type, payload) => {
        if (type !== 'form-save') return;
        const cfg = payload as { fields: DesignField[]; logic: unknown[]; assoc: unknown[] };
        try {
          await saveCreateForm(
            objectType,
            cfg.fields.map((f) => ({ field: f.key, required: Boolean(f.req) })),
          );
          writeExtras(objectType, { logic: cfg.logic ?? [], assoc: cfg.assoc ?? [] });
        } catch (err) {
          toast(errorText(err), 'danger', { durationMs: 8000 });
        }
      },
    };
  }, [objectType, from, toast]);

  // Full screen like HubSpot's form editor: no CRM sidebar or topbar, the editor's own Back bar only.
  return (
    <DesignFrame
      key={objectType}
      page="form-editor"
      title="Edit form"
      live={live}
      className="crm-design-frame--full"
    />
  );
}

export function FormEditorLive() {
  return (
    <Suspense>
      <FormEditor />
    </Suspense>
  );
}
