'use client';

// LR2: moving a lead between stages, with what asks first: a stage's required fields (24 Nov
// design stageGate), then Qualify / Disqualify (HUB-728) and Convert. Moved out of LeadActions so
// the lead page's buttons and the design's Lead stage tracker card (record-tabs.js:469-490, live
// design) share one flow; the contact page's card runs one per lead.
import { useEffect, useRef, useState, type ReactNode } from 'react';
import { createPortal } from 'react-dom';
import { useToast } from '@/components/crm/ToastProvider';
import type { PipelineStage } from '@/features/pipelines/api.client';
import { requiredNames, stageRequirementsOf } from '@/features/pipelines/stageRules';
import { useRecordStageGate } from '@/features/pipelines/ui/useStageGate';
import { changeObjectRecordStage } from '../../api.client';
import { saveErrorText } from '../../errors';
import { closedStageDialog, DISQUALIFICATION_REASON, disqualificationReasons } from '../../leads';
import type { CustomValues, ObjectRecord } from '../../types';
import type { ObjectSchema } from '../../useObjectSchema';
import { ConvertLeadDrawer } from './ConvertLeadDrawer';
import { EnrollLeadDialog } from './EnrollLeadDialog';
import { DisqualifyDialog, QualifyDialog } from './LeadStageDialogs';

export type LeadDialog = 'qualify' | 'disqualify' | 'convert' | 'enroll' | null;

/** The pipeline's first live won stage (Qualified) and lost stage (Disqualified). */
export function closedStagesOf(schema: ObjectSchema, pipelineId: string | null) {
  const pipeline = schema.pipelines.find((p) => p.id === pipelineId);
  const live = (pipeline?.stages ?? []).filter((s) => !s.archived);
  return {
    pipeline,
    won: live.find((s) => s.stageType === 'won') ?? null,
    lost: live.find((s) => s.stageType === 'lost') ?? null,
  };
}

export interface LeadStageMove {
  pipeline: ReturnType<typeof closedStagesOf>['pipeline'];
  current: PipelineStage | null;
  /** The stage Qualify and Disqualify move to: the one picked, else the pipeline's first. */
  won: PipelineStage | null;
  lost: PipelineStage | null;
  moving: boolean;
  /** Asks what the stage needs first, then moves the lead there. */
  startMove: (stage: PipelineStage) => Promise<void>;
  /** Opens Convert to deal or Enroll in sequence (the lead page's buttons). */
  openDialog: (dialog: LeadDialog) => void;
  /** The dialogs and drawers, rendered once by whoever owns this flow (portalled to <body>). */
  dialogs: ReactNode;
}

export function useLeadStageMove({
  schema,
  record,
  onChange,
  onRefresh,
  onConverted,
}: {
  schema: ObjectSchema;
  record: ObjectRecord;
  onChange: (record: ObjectRecord) => void;
  /** Reloads what a move or a conversion changes elsewhere on the page (linked deal, timeline). */
  onRefresh?: () => void;
  /**
   * LR2: after a conversion only, e.g. the contact page's Deals card, which gains the new deal
   * (the conversion links the lead's contacts to it).
   */
  onConverted?: () => void;
}): LeadStageMove {
  const toast = useToast();
  const [open, setOpen] = useState<LeadDialog>(null);
  /** The stage the dialog moves to: the one picked, else the pipeline's first. */
  const [targetId, setTargetId] = useState<string | null>(null);
  // The dialogs go to <body>: inside a record column they would sit under the page.
  const [portal, setPortal] = useState<HTMLElement | null>(null);
  useEffect(() => setPortal(document.body), []);
  const key = schema.definition.key;
  const { pipeline, won: firstWon, lost: firstLost } = closedStagesOf(schema, record.pipelineId);
  const current = pipeline?.stages.find((s) => s.id === record.stageId) ?? null;
  const target = pipeline?.stages.find((s) => s.id === targetId) ?? null;
  const won = target?.stageType === 'won' ? target : firstWon;
  const lost = target?.stageType === 'lost' ? target : firstLost;
  const name = record.displayName || 'this lead';

  // 24 Nov design (stageGate): a stage's required fields are asked for first, then Qualified and
  // Disqualified ask as their buttons do; other stages move at once.
  const gate = useRecordStageGate(schema);
  /** The record as last saved here (the gate saves fields before the props catch up). */
  const latest = useRef(record);
  latest.current = record.updatedAt >= latest.current.updatedAt ? record : latest.current;
  const [moving, setMoving] = useState(false);

  const close = () => {
    setOpen(null);
    setTargetId(null);
  };

  /**
   * Moves the lead; the message of a refusal is thrown for the dialog to show. False when the
   * required-fields prompt (a refused move asks again) was cancelled.
   */
  const moveTo = async (stageId: string, fields?: CustomValues): Promise<boolean> => {
    const send = (from: ObjectRecord) =>
      changeObjectRecordStage(key, from.id, {
        stageId,
        updatedAt: from.updatedAt,
        ...(fields ? { customProperties: fields } : {}),
      });
    try {
      let saved: ObjectRecord;
      try {
        saved = await send(latest.current);
      } catch (err) {
        // Required fields set meanwhile: ask for the ones the API names, then move again.
        const names = stageRequirementsOf(err);
        const stage = pipeline?.stages.find((s) => s.id === stageId);
        if (!names || !stage) throw err;
        const filled = await gate.fillRequired(latest.current, stage, names);
        if (!filled) return false;
        saved = await send(filled);
      }
      latest.current = saved;
      onChange({ ...saved, linkCounts: record.linkCounts });
      close();
      onRefresh?.();
      return true;
    } catch (err) {
      throw new Error(saveErrorText(err, schema.defs));
    }
  };

  const startMove = async (stage: PipelineStage) => {
    if (requiredNames(stage).length) {
      const filled = await gate.fillRequired(latest.current, stage);
      if (!filled) return;
      latest.current = filled;
      onChange(filled);
    }
    const kind = closedStageDialog(stage);
    if (kind) {
      setTargetId(stage.id);
      setOpen(kind);
      return;
    }
    setMoving(true);
    try {
      // The design card's toast (record-tabs.js:487, live design).
      if (await moveTo(stage.id)) toast(`${name} moved to ${stage.name}`, 'success');
    } catch (err) {
      toast(err instanceof Error ? err.message : String(err), 'danger', { durationMs: 8000 });
    } finally {
      setMoving(false);
    }
  };

  const dialogs = portal
    ? createPortal(
        <>
          <QualifyDialog
            open={open === 'qualify'}
            leadName={name}
            stageName={won?.name ?? 'Qualified'}
            converted={Boolean(record.convertedDealId)}
            onClose={close}
            onConvert={() => setOpen('convert')}
            onQualify={async () => {
              if (!won) return;
              if (await moveTo(won.id)) toast(`${name} qualified.`, 'success');
            }}
          />
          <DisqualifyDialog
            open={open === 'disqualify'}
            leadName={name}
            reasons={disqualificationReasons(schema.defs)}
            initialReason={
              (record.customProperties[DISQUALIFICATION_REASON] as string | undefined) ?? null
            }
            onClose={close}
            onConfirm={async (fields) => {
              if (!lost) return;
              if (await moveTo(lost.id, fields)) toast(`${name} disqualified.`, 'success');
            }}
          />
          <ConvertLeadDrawer
            open={open === 'convert'}
            objectKey={key}
            lead={record}
            owners={schema.owners}
            onClose={close}
            onConverted={(lead) => {
              if (lead) onChange({ ...lead, linkCounts: record.linkCounts });
              // The new deal is linked to the lead: show it in the Deals card and timeline.
              onRefresh?.();
              onConverted?.();
            }}
          />
          <EnrollLeadDialog
            open={open === 'enroll'}
            objectKey={key}
            leadId={record.id}
            leadName={name}
            onClose={close}
            onEnrolled={() => {
              setOpen(null);
              toast('Enrolled in the sequence.', 'success');
            }}
          />
          {gate.dialogs}
        </>,
        portal,
      )
    : null;

  return {
    pipeline,
    current,
    won,
    lost,
    moving,
    startMove,
    openDialog: setOpen,
    dialogs,
  };
}
