'use client';

// The stage gate of the 24 Nov design (list-page.js stageGate): before a record moves into a
// stage, its required properties the record lacks are asked for and saved (the design saves them
// on "Save and move", before the stage's own dialog: lost reason, Qualify / Disqualify). A ticket
// closes with no prompt of its own, as in HubSpot (D-2): the API sets its Close date. Every view
// that moves records (boards, record headers, stage bars) uses these.
import { useCallback, useMemo, type ReactNode } from 'react';
import type { CustomPropertyDefinition } from '@/features/custom-properties/api.client';
import { updateDeal } from '@/features/deals/api.client';
import type { Deal, UpdateDealBody } from '@/features/deals/types';
import { updateObjectRecord } from '@/features/objects/api.client';
import { saveErrorText } from '@/features/objects/errors';
import { isLeadObject } from '@/features/objects/leads';
import type { CustomValues, ObjectRecord } from '@/features/objects/types';
import type { ObjectSchema } from '@/features/objects/useObjectSchema';
import type { Owner } from '@/features/owners/api.client';
import { errorText } from '@/lib/api/errors';
import type { StageProperty } from '../api.client';
import { dealFieldSpecs, recordFieldSpecs, specsFor, type StageValues } from '../stageFields';
import {
  dealPropertyValue,
  missingProperties,
  recordPropertyValue,
  stageColor,
  stagePropertiesOf,
} from '../stageRules';
import { useStageRequirementsPrompt } from './StagePrompts';

type GateStage = {
  id: string;
  name: string;
  stageType?: string | null;
  color?: string | null;
  properties?: StageProperty[];
};

/** Custom object records: the required-fields prompt. */
export function useRecordStageGate(schema: ObjectSchema): {
  /**
   * Asks for the stage's required fields the record lacks (or `names`, from a refused move) and
   * saves them. The record to move (saved), or null when the prompt was cancelled.
   */
  fillRequired: (
    record: ObjectRecord,
    stage: GateStage,
    names?: string[] | null,
  ) => Promise<ObjectRecord | null>;
  dialogs: ReactNode;
} {
  const required = useStageRequirementsPrompt();
  const { definition, defs, owners } = schema;
  const specs = useMemo(
    () => recordFieldSpecs({ singular: definition.singularLabel, defs, owners }),
    [definition.singularLabel, defs, owners],
  );
  const lead = isLeadObject(definition);
  const ask = required.ask;

  const fillRequired = useCallback(
    async (record: ObjectRecord, stage: GateStage, names?: string[] | null) => {
      const missing = names ?? missingProperties(stage, (n) => recordPropertyValue(record, n));
      if (!missing.length) return record;
      let saved: ObjectRecord | null = null;
      const ok = await ask({
        variant: 'record',
        recordName: record.displayName || `this ${definition.singularLabel.toLowerCase()}`,
        stageName: stage.name,
        stageColor: stageColor(stage, { lead }),
        missing: specsFor(missing, specs),
        plural: definition.pluralLabel,
        submit: async (values: StageValues) => {
          try {
            saved = await updateObjectRecord(definition.key, record.id, {
              ...('ownerId' in values.standard
                ? { ownerId: (values.standard.ownerId as string | null) ?? null }
                : {}),
              ...(Object.keys(values.custom).length
                ? { customProperties: values.custom as CustomValues }
                : {}),
              updatedAt: record.updatedAt,
            });
          } catch (err) {
            throw new Error(saveErrorText(err, defs));
          }
        },
      });
      return ok && saved ? { ...(saved as ObjectRecord), linkCounts: record.linkCounts } : null;
    },
    [ask, definition, defs, lead, specs],
  );

  return { fillRequired, dialogs: required.dialog };
}

/** Deals: the "Required properties for <stage>" prompt (conditional logic rule's fields). */
export function useDealStageGate(opts: {
  defs: CustomPropertyDefinition[];
  owners: Owner[];
  dealTypes: ReadonlyArray<{ value: string; label: string }>;
}): {
  /**
   * Asks for the stage's required properties the deal lacks (or `names`, from a refused move),
   * with the rule's other properties, and saves them. The deal to move, or null when cancelled.
   */
  fillRequired: (deal: Deal, stage: GateStage, names?: string[] | null) => Promise<Deal | null>;
  /**
   * DL2: the same prompt for a deal not created yet (the create form's values in `draft`). The
   * values picked, to send with the create; none to add when nothing is missing; null when
   * cancelled. Saves nothing itself.
   */
  askForCreate: (draft: DealDraft, stage: GateStage) => Promise<StageValues | null>;
  dialog: ReactNode;
} {
  const prompt = useStageRequirementsPrompt();
  const { defs, owners, dealTypes } = opts;
  const specs = useMemo(
    () => dealFieldSpecs({ defs, owners, dealTypes }),
    [defs, owners, dealTypes],
  );
  const ask = prompt.ask;
  const fillRequired = useCallback(
    async (deal: Deal, stage: GateStage, names?: string[] | null) => {
      const missing = names ?? missingProperties(stage, (n) => dealPropertyValue(deal, n));
      if (!missing.length) return deal;
      const shown = stagePropertiesOf(stage)
        .map((p) => p.name)
        .filter((n) => !missing.includes(n));
      let saved: Deal | null = null;
      const ok = await ask({
        variant: 'deal',
        recordName: deal.name,
        stageName: stage.name,
        stageColor: stageColor(stage),
        missing: specsFor(missing, specs),
        optional: specsFor(shown, specs),
        current: Object.fromEntries(shown.map((n) => [n, dealPropertyValue(deal, n)])),
        submit: async (values: StageValues) => {
          const body: UpdateDealBody = {
            ...(values.standard as Partial<UpdateDealBody>),
            ...(Object.keys(values.custom).length
              ? { customProperties: values.custom as UpdateDealBody['customProperties'] }
              : {}),
            updatedAt: deal.updatedAt,
          };
          try {
            saved = await updateDeal(deal.id, body);
          } catch (err) {
            throw new Error(errorText(err));
          }
        },
      });
      return ok ? saved : null;
    },
    [ask, specs],
  );
  const askForCreate = useCallback(
    async (draft: DealDraft, stage: GateStage) => {
      const missing = missingProperties(stage, (n) => dealPropertyValue(draft, n));
      if (!missing.length) return { standard: {}, custom: {} };
      const shown = stagePropertiesOf(stage)
        .map((p) => p.name)
        .filter((n) => !missing.includes(n));
      let picked: StageValues | null = null;
      const ok = await ask({
        variant: 'deal',
        creating: true,
        recordName: draft.name || 'this deal',
        stageName: stage.name,
        stageColor: stageColor(stage),
        missing: specsFor(missing, specs),
        optional: specsFor(shown, specs),
        current: Object.fromEntries(shown.map((n) => [n, dealPropertyValue(draft, n)])),
        submit: async (values: StageValues) => {
          picked = values;
        },
      });
      return ok ? picked : null;
    },
    [ask, specs],
  );
  return { fillRequired, askForCreate, dialog: prompt.dialog };
}

/** A deal's values as the stage rules read them (`dealPropertyValue`): the create form's too. */
export type DealDraft = Parameters<typeof dealPropertyValue>[0];
