'use client';

// LR2: the design's "Lead stage tracker" card (live design record-tabs.js:469-490, with
// components/lead-pipeline.js `stepper`): the lead's name, "<pipeline> · <owner | No owner>" and
// the colour-coded stage stepper. A stage click asks for what the stage needs, then moves the lead
// (`useLeadStageMove`). The gear opens Settings › Objects › Leads › Pipelines (record-tabs.js:473).
// The design draws it on the contact page (record-layout.js:121); the lead page gets it in its
// right column too, by the user's call (25 Nov 2026), in place of its left summary's stepper.
import Link from 'next/link';
import { useCallback, useEffect, useRef, useState, type ReactNode } from 'react';
import { useCurrentUser } from '@/features/auth/CurrentUser';
import { scopeCovers } from '@/features/auth/record-access';
import { CollapsibleCard } from '@/features/contacts/ui/CollapsibleCard';
import { CrmIcon } from '@/components/crm/CrmIcon';
import { stageDays } from '@/features/pipelines/stageRules';
import { StageStepper } from '@/features/pipelines/ui/StageStepper';
import { settingsHref } from '@/features/settings/ui/object-settings/config';
import { errorText } from '@/lib/api/errors';
import { getObjectRecord, listLinkedRecords } from '../../api.client';
import { objectRecordPath } from '../../paths';
import type { LinkedRecord, ObjectRecord } from '../../types';
import { useObjectSchema, type ObjectSchema } from '../../useObjectSchema';
import { Icon } from '../icons';
import type { LeadStageMove } from './useLeadStageMove';
import { useLeadStageMove } from './useLeadStageMove';

export const LEAD_STAGE_TITLE = 'Lead stage tracker';
/** The design card's text without a lead (record-tabs.js:471). */
export const LEAD_STAGE_EMPTY = 'Track the prospecting activities associated with this record.';
/** The Leads object's key: the one the lead record page and its layout use (eventLayout.ts). */
const LEAD_KEY = 'lead';
/** Leads asked for per page of the contact's card. */
const PAGE = 25;

/** "<pipeline> · <owner>", "No owner" without one (record-tabs.js:472). */
export function leadStageMeta(pipelineName: string | null | undefined, owner: string | null) {
  return `${pipelineName || 'Lead pipeline'} · ${owner || 'No owner'}`;
}

/** The gear: Settings › Objects › Leads › Pipelines, for those who may manage settings. */
function PipelinesGear({ className, icon }: { className: string; icon: ReactNode }) {
  const me = useCurrentUser();
  if (!me.permissionSet.rules.app.manage_settings) return null;
  return (
    <Link
      className={className}
      href={settingsHref(LEAD_KEY, 'pipelines')}
      aria-label="Edit lead pipeline stages"
      title="Edit stages, colors and required fields"
    >
      {icon}
    </Link>
  );
}

/**
 * One lead: its name (a link, left out on the lead's own page), pipeline and owner, and the
 * stepper. After a move made here, focus goes to the new current stage (record-tabs.js:486).
 */
export function LeadStageBlock({
  record,
  move,
  canEdit,
  link,
}: {
  record: ObjectRecord;
  move: LeadStageMove;
  canEdit: boolean;
  /** The lead page's path, or null on the lead's own page. */
  link: string | null;
}) {
  const box = useRef<HTMLDivElement>(null);
  const movedHere = useRef(false);
  useEffect(() => {
    if (!movedHere.current) return;
    movedHere.current = false;
    const current = box.current?.querySelector<HTMLElement>('.lpl-step.is-current .lpl-step__btn');
    if (current) {
      current.setAttribute('tabindex', '-1');
      current.focus();
    }
  }, [record.stageId]);
  const { pipeline, current, moving, startMove } = move;
  return (
    <div ref={box}>
      <div className="rt-lead">
        {link ? (
          <Link className="rt-lead__name" href={link}>
            {record.displayName || 'Untitled'}
          </Link>
        ) : null}
        <span className="rt-lead__meta">
          {leadStageMeta(pipeline?.name, record.owner?.name ?? null)}
        </span>
      </div>
      {pipeline && current ? (
        <StageStepper
          stages={pipeline.stages}
          currentId={current.id}
          days={stageDays(record)}
          label="Lead stage"
          lead
          interactive={canEdit}
          busy={moving}
          onSelect={(stage) => {
            movedHere.current = true;
            void startMove(stage);
          }}
        />
      ) : null}
    </div>
  );
}

/** The lead record page's right-column card (its `evr-side` look). The page owns `move`. */
export function LeadStageSideCard({
  record,
  move,
  canEdit,
}: {
  record: ObjectRecord;
  move: LeadStageMove;
  canEdit: boolean;
}) {
  const [open, setOpen] = useState(true);
  return (
    <section className="evr-side">
      <header className="evr-side__head">
        <button
          type="button"
          className="evr-card__toggle"
          aria-expanded={open}
          onClick={() => setOpen((v) => !v)}
        >
          <Icon name={open ? 'chevronDown' : 'chevronRight'} size={12} />
          <span>{LEAD_STAGE_TITLE}</span>
        </button>
        <PipelinesGear
          className="ev-iconbtn ev-iconbtn--xs"
          icon={<Icon name="gear" size={12} />}
        />
      </header>
      {open ? (
        move.pipeline && move.current ? (
          <LeadStageBlock record={record} move={move} canEdit={canEdit} link={null} />
        ) : (
          <p className="evr-side__empty">{LEAD_STAGE_EMPTY}</p>
        )
      ) : null}
    </section>
  );
}

/** One of the contact's leads: loaded in full (stage age, fields the stage asks for). */
function ContactLead({
  row,
  schema,
  onConverted,
}: {
  row: LinkedRecord;
  schema: ObjectSchema;
  onConverted?: () => void;
}) {
  const me = useCurrentUser();
  const [record, setRecord] = useState<ObjectRecord | null>(null);
  const [error, setError] = useState<string | null>(null);
  useEffect(() => {
    let alive = true;
    setError(null);
    getObjectRecord(LEAD_KEY, row.id).then(
      (next) => {
        if (alive) setRecord(next);
      },
      (err: unknown) => {
        if (alive) setError(errorText(err));
      },
    );
    return () => {
      alive = false;
    };
  }, [row.id]);
  const link = objectRecordPath(LEAD_KEY, row.id);
  if (!record) {
    return (
      <div className="rt-lead">
        <Link className="rt-lead__name" href={link}>
          {row.name || 'Untitled'}
        </Link>
        <span className="rt-lead__meta">
          {error ? `Couldn't load this lead's stage: ${error}` : 'Loading…'}
        </span>
      </div>
    );
  }
  // Leads follow the company rules, as the lead page and the API do.
  const canEdit = scopeCovers(me.permissionSet.rules.objects.company.edit, record.owner?.id, me);
  return (
    <ContactLeadStages
      record={record}
      schema={schema}
      canEdit={canEdit}
      onChange={setRecord}
      onConverted={onConverted}
    />
  );
}

function ContactLeadStages({
  record,
  schema,
  canEdit,
  onChange,
  onConverted,
}: {
  record: ObjectRecord;
  schema: ObjectSchema;
  canEdit: boolean;
  onChange: (record: ObjectRecord) => void;
  onConverted?: () => void;
}) {
  const move = useLeadStageMove({ schema, record, onChange, onConverted });
  return (
    <>
      <LeadStageBlock
        record={record}
        move={move}
        canEdit={canEdit}
        link={objectRecordPath(LEAD_KEY, record.id)}
      />
      {move.dialogs}
    </>
  );
}

/**
 * The contact page's card (record-layout.js:121): one block per lead linked to the contact (the
 * user's call; the design has one), else the design's text. No Add (the design's is "soon").
 */
export function ContactLeadStageCard({
  contactId,
  onConverted,
}: {
  contactId: string;
  /** Reloads the contact (its Deals card) after a lead here is converted to a deal. */
  onConverted?: () => void;
}) {
  const lead = useObjectSchema(LEAD_KEY);
  const [rows, setRows] = useState<LinkedRecord[] | null>(null);
  const [cursor, setCursor] = useState<string | null>(null);
  const [error, setError] = useState<string | null>(null);
  const [busy, setBusy] = useState(false);
  const ready = lead.status === 'ready';

  const load = useCallback(
    async (after?: string) => {
      const page = await listLinkedRecords({
        fromType: 'contact',
        fromId: contactId,
        toType: LEAD_KEY,
        limit: PAGE,
        ...(after ? { cursor: after } : {}),
      });
      return page;
    },
    [contactId],
  );

  useEffect(() => {
    if (!ready) return;
    let alive = true;
    setRows(null);
    setError(null);
    load().then(
      (page) => {
        if (!alive) return;
        setRows(page.data);
        setCursor(page.nextCursor ?? null);
      },
      (err: unknown) => {
        if (alive) setError(errorText(err));
      },
    );
    return () => {
      alive = false;
    };
  }, [ready, load]);

  const more = async () => {
    if (!cursor) return;
    setBusy(true);
    try {
      const page = await load(cursor);
      setRows((prev) => [...(prev ?? []), ...page.data]);
      setCursor(page.nextCursor ?? null);
    } catch (err) {
      setError(errorText(err));
    } finally {
      setBusy(false);
    }
  };

  let body;
  if (lead.status === 'missing' || lead.status === 'moved') {
    // A business without the Leads object: the design's text.
    body = <p className="rt-rtext">{LEAD_STAGE_EMPTY}</p>;
  } else if (lead.status === 'error' || (error && !rows)) {
    body = (
      <p className="rt-rtext" role="alert">
        Couldn&apos;t load leads: {lead.status === 'error' ? lead.error : error}
      </p>
    );
  } else if (lead.status === 'loading' || !rows) {
    body = <p className="rt-rtext">Loading…</p>;
  } else if (!rows.length) {
    body = <p className="rt-rtext">{LEAD_STAGE_EMPTY}</p>;
  } else {
    body = (
      <div className="rt-leads">
        {rows.map((row) => (
          <ContactLead key={row.id} row={row} schema={lead.schema} onConverted={onConverted} />
        ))}
        {error ? (
          <p className="rt-rtext" role="alert">
            Couldn&apos;t load more leads: {error}
          </p>
        ) : null}
        {cursor ? (
          <button
            type="button"
            className="rp-card-link"
            disabled={busy}
            onClick={() => void more()}
          >
            {busy ? 'Loading…' : 'Show more leads'}
          </button>
        ) : null}
      </div>
    );
  }

  return (
    <CollapsibleCard
      title={LEAD_STAGE_TITLE}
      cardId="r-leadstage"
      action={
        <PipelinesGear
          className="crm-card-gear"
          icon={<CrmIcon name="settings" className="iconSize-16" />}
        />
      }
    >
      {body}
    </CollapsibleCard>
  );
}
