'use client';

// The lead page's actions (HUB-340): the converted deal, and Qualify / Disqualify / Convert to
// deal / Enroll in sequence. LR2: the stage flow lives in `useLeadStageMove`, shared with the
// right column's Lead stage tracker card, which now holds the stage stepper.
import Link from 'next/link';
import { useEffect } from 'react';
import { useCurrentUser } from '@/features/auth/CurrentUser';
import { stageDays } from '@/features/pipelines/stageRules';
import { StageStepper } from '@/features/pipelines/ui/StageStepper';
import type { ObjectRecord } from '../../types';
import type { LeadStageMove } from './useLeadStageMove';

/** HUB-728: a closed stage picked elsewhere on the page (the header's stage select). */
export interface LeadStageRequest {
  stageId: string;
  /** A new one for every pick, so picking the same stage again opens the dialog again. */
  nonce: number;
}

export function LeadActions({
  record,
  canEdit,
  move,
  stageRequest,
  showStepper,
}: {
  record: ObjectRecord;
  canEdit: boolean;
  /** The page's stage flow (`useLeadStageMove`); this component renders its dialogs. */
  move: LeadStageMove;
  /** Opens the Qualify / Disqualify dialog for this stage instead of moving the lead at once. */
  stageRequest?: LeadStageRequest | null;
  /**
   * LR2: the stage stepper here, for a page without the right column's Lead stage tracker card
   * (a Leads object not keyed `lead`, which reads no record layout).
   */
  showStepper: boolean;
}) {
  const me = useCurrentUser();
  const { pipeline, current, won, lost, moving, startMove, openDialog, dialogs } = move;

  // The header's stage select picked a stage that asks first: ask as the buttons do.
  useEffect(() => {
    if (!stageRequest) return;
    const stage = pipeline?.stages.find((s) => s.id === stageRequest.stageId);
    if (stage) void startMove(stage);
    // Only a new request opens the dialog, not a change of the pipeline list.
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [stageRequest]);

  const days = stageDays(record);
  const canEnroll = Boolean(me.permissionSet.rules.app.use_sequences);
  const noEdit = "Your permissions don't allow you to edit this record";

  return (
    <div className="crm-about-contact crm-gap-3" style={{ marginTop: 12 }}>
      {showStepper && pipeline && current ? (
        // 24 Nov design: the lead stage stepper, in the stages' colours, with "In stage: Nd".
        <StageStepper
          stages={pipeline.stages}
          currentId={current.id}
          days={days}
          label="Lead stage"
          lead
          interactive={canEdit}
          busy={moving}
          onSelect={(stage) => void startMove(stage)}
        />
      ) : null}
      {record.convertedDealId ? (
        <p className="crm-fs-8 crm-mb-0">
          <span className="ev-chip">Converted</span>{' '}
          <Link href={`/deals/${record.convertedDealId}`}>Open deal</Link>
        </p>
      ) : null}
      <div style={{ display: 'flex', flexWrap: 'wrap', gap: 8 }}>
        <button
          type="button"
          className="btn-crm btn-crm--outline btn-crm--sm"
          disabled={!canEdit || !won || current?.id === won.id}
          title={canEdit ? undefined : noEdit}
          onClick={() => {
            if (won) void startMove(won);
          }}
        >
          Qualify
        </button>
        <button
          type="button"
          className="btn-crm btn-crm--outline btn-crm--sm"
          disabled={!canEdit || !lost || current?.id === lost.id}
          title={canEdit ? undefined : noEdit}
          onClick={() => {
            if (lost) void startMove(lost);
          }}
        >
          Disqualify
        </button>
        {!record.convertedDealId ? (
          <button
            type="button"
            className="btn-crm btn-crm--primary btn-crm--sm"
            disabled={!canEdit || current?.stageType === 'lost'}
            title={
              !canEdit
                ? noEdit
                : current?.stageType === 'lost'
                  ? 'Reopen the lead before converting it'
                  : undefined
            }
            onClick={() => openDialog('convert')}
          >
            Convert to deal
          </button>
        ) : null}
        <button
          type="button"
          className="btn-crm btn-crm--outline btn-crm--sm"
          disabled={!canEnroll}
          title={canEnroll ? undefined : 'Your permissions do not allow using sequences'}
          onClick={() => openDialog('enroll')}
        >
          Enroll in sequence
        </button>
      </div>
      {dialogs}
    </div>
  );
}
