'use client';

// LD3: the lead preview's additions in the 26 Nov design (list-page.js:4112, 4146-4148): a
// "Lead stage" section with the interactive stepper before "About this lead", and Actions ›
// Convert to deal and Disqualify. They run the lead page's own flow (`useLeadStageMove`: required
// fields, then Qualify / Disqualify / Convert), so the rules and dialogs are the same.
import { useEffect, useRef, useState, type ReactNode } from 'react';
import type { LpMenuItem } from '@/features/list-page/ui/LpPopover';
import { LpIcon } from '@/features/list-page/ui/LpIcon';
import type { PreviewExtras } from '@/features/list-page/ui/RecordPreviewView';
import { stageDays } from '@/features/pipelines/stageRules';
import { StageStepper } from '@/features/pipelines/ui/StageStepper';
import type { ObjectRecord } from '../../types';
import type { ObjectSchema } from '../../useObjectSchema';
import { useLeadStageMove, type LeadStageMove } from './useLeadStageMove';

/** Stands in until the preview loaded its lead: the flow's dialogs stay closed meanwhile. */
const NO_LEAD: ObjectRecord = {
  id: '',
  objectKey: '',
  displayName: null,
  owner: null,
  source: '',
  hubspotId: null,
  pipelineId: null,
  stageId: null,
  customProperties: {},
  createdAt: '',
  updatedAt: '',
  deletedAt: null,
};

/**
 * The design's Actions additions, after View all properties (:4146-4148): Convert to deal while
 * not converted (off on a lost stage, as the lead page's button), Disqualify unless the lead is
 * already in a lost stage. Both off without the edit right.
 */
export function leadPreviewActions(
  record: ObjectRecord,
  move: Pick<LeadStageMove, 'current' | 'lost' | 'startMove' | 'openDialog'>,
  canEdit: boolean,
): LpMenuItem[] {
  const lostNow = move.current?.stageType === 'lost';
  return [
    ...(record.convertedDealId
      ? []
      : [
          {
            key: 'lead-convert',
            label: 'Convert to deal',
            icon: 'deal' as const,
            disabled: !canEdit || lostNow,
            onSelect: () => move.openDialog('convert'),
          },
        ]),
    ...(lostNow
      ? []
      : [
          {
            key: 'lead-disqualify',
            label: 'Disqualify',
            icon: 'x' as const,
            disabled: !canEdit || !move.lost,
            onSelect: () => {
              if (move.lost) void move.startMove(move.lost);
            },
          },
        ]),
  ];
}

/** "Lead stage": a collapsible section with the stepper (design :4112). */
function LeadStageSection({
  record,
  move,
  canEdit,
  reload,
}: {
  record: ObjectRecord;
  move: LeadStageMove;
  canEdit: boolean;
  /** Loads the preview again after a move (About shows the stage too). */
  reload: () => void;
}) {
  const [open, setOpen] = useState(true);
  const seen = useRef(record.updatedAt);
  useEffect(() => {
    if (seen.current === record.updatedAt) return;
    seen.current = record.updatedAt;
    reload();
  }, [record.updatedAt, reload]);
  const { pipeline, current } = move;
  if (!pipeline || !current) return null;
  return (
    <section className="lp-pv__sec">
      <h3>
        <button
          type="button"
          className="lp-pv__sh"
          aria-expanded={open}
          onClick={() => setOpen((v) => !v)}
        >
          <LpIcon name="caret" />
          Lead stage
        </button>
      </h3>
      {open ? (
        <div className="lp-pv__stepper">
          <StageStepper
            stages={pipeline.stages}
            currentId={current.id}
            days={stageDays(record)}
            label="Lead stage"
            lead
            interactive={canEdit}
            busy={move.moving}
            onSelect={(stage) => void move.startMove(stage)}
          />
        </div>
      ) : null}
    </section>
  );
}

/**
 * Owns the lead flow for the list's preview panel. `record` is the lead the preview loaded (the
 * list's `load` hands it over); `children` gets the panel's extras, or nothing before it loaded.
 */
export function LeadPreviewFlow({
  schema,
  recordId,
  record,
  canEdit,
  onChange,
  children,
}: {
  schema: ObjectSchema;
  /** The previewed id: a lead loaded for another id is not shown. */
  recordId: string | null;
  record: ObjectRecord | null;
  canEdit: (record: ObjectRecord) => boolean;
  /** The lead after a move or conversion: keep it and refresh the list. */
  onChange: (record: ObjectRecord) => void;
  /**
   * Gets the panel's extras, always a function: the panel's Escape and focus set-up depends on
   * whether it has extras, so it must not change when the lead arrives. Empty until then.
   */
  children: (extras: (reload: () => void) => PreviewExtras) => ReactNode;
}) {
  const shown = record && record.id === recordId ? record : null;
  const move = useLeadStageMove({
    schema,
    record: shown ?? NO_LEAD,
    onChange,
  });
  const editable = shown ? canEdit(shown) : false;
  return (
    <>
      {children((reload) =>
        shown
          ? {
              beforeAbout: (
                <LeadStageSection record={shown} move={move} canEdit={editable} reload={reload} />
              ),
              actionItems: leadPreviewActions(shown, move, editable),
            }
          : {},
      )}
      {shown ? move.dialogs : null}
    </>
  );
}
