'use client';

import { useEffect, useState } from 'react';
import { Field, FormDrawer } from '@/components/crm/FormDrawer';
import { useToast } from '@/components/crm/ToastProvider';
import { actionErrorText } from '@/features/contacts/ui/actions/shared';
import { changeDealStage, getDeal, listPipelines } from '@/features/deals/api.client';
import { reopensDeal } from '@/features/deals/stageMove';
import type { Deal, Pipeline, PipelineStage } from '@/features/deals/types';
import { requiredNames, stageRequirementsOf } from '@/features/pipelines/stageRules';
import {
  attachContract,
  useClosedLostReason,
  useClosedWonReason,
  type LostAnswer,
  type WonAnswerWithContract,
} from '@/features/deals/ui/actions/ClosedLostDialog';

function activeStages(pipeline: Pipeline | undefined) {
  return (pipeline?.stages ?? [])
    .filter((s) => !s.archived)
    .sort((a, b) => a.displayOrder - b.displayOrder);
}

/**
 * Moves a deal to another pipeline and one of its stages (POST /deals/:id/stage with
 * `pipelineId`), so the move is recorded in the stage history like any stage change.
 */
export function MoveDealPipelineDrawer({
  open,
  onClose,
  deal,
  onMoved,
  fillRequired,
  confirmReopen,
}: {
  open: boolean;
  onClose: () => void;
  deal: Deal;
  onMoved: (updated: Deal) => void;
  /**
   * DL1: the page's stage gate (`useDealStageGate().fillRequired`): asks the stage's required
   * properties the deal lacks (or `names`, from a refused move) and saves them; null when
   * cancelled. Without it the API's refusal shows as a toast, as before.
   */
  fillRequired?: (
    deal: Deal,
    stage: PipelineStage,
    names?: string[] | null,
  ) => Promise<Deal | null>;
  /** DL1: asked before a won or lost deal moves to an open stage; false keeps it where it is. */
  confirmReopen?: (from: Deal['stage'], to: PipelineStage) => Promise<boolean>;
}) {
  const toast = useToast();
  const lostReason = useClosedLostReason();
  const wonReason = useClosedWonReason();
  const [pipelines, setPipelines] = useState<Pipeline[]>([]);
  const [loaded, setLoaded] = useState(false);
  const [pipelineId, setPipelineId] = useState('');
  const [stageId, setStageId] = useState('');

  useEffect(() => {
    if (!open) return;
    let cancelled = false;
    setLoaded(false);
    listPipelines().then(
      (res) => {
        if (cancelled) return;
        const active = res.data.filter((p) => !p.archived);
        setPipelines(active);
        // Start on where the deal is now (HubSpot does too): picking another pipeline by
        // default moved deals into the wrong one when reps saved without looking (QA #4).
        const current = active.find((p) => p.id === deal.pipeline.id) ?? active[0];
        setPipelineId(current?.id ?? '');
        const stages = activeStages(current);
        setStageId((stages.find((s) => s.id === deal.stage.id) ?? stages[0])?.id ?? '');
        setLoaded(true);
      },
      (err) => {
        if (cancelled) return;
        setPipelines([]);
        setLoaded(true);
        toast(actionErrorText(err), 'danger', { durationMs: 8000 });
      },
    );
    return () => {
      cancelled = true;
    };
  }, [open, deal.pipeline.id, deal.stage.id, toast]);

  const pipeline = pipelines.find((p) => p.id === pipelineId);
  const stages = activeStages(pipeline);

  const onSubmit = async () => {
    const stage = stages.find((s) => s.id === stageId);
    if (!pipeline || !stage) {
      toast('Pick a pipeline and a stage', 'danger');
      return false;
    }
    if (stage.id === deal.stage.id) {
      toast('The deal is already there: pick another pipeline or stage', 'info');
      return false;
    }
    // DL1: as the stage bar: reopening asks first, then the stage's required properties.
    if (
      confirmReopen &&
      reopensDeal(deal.stage, stage) &&
      !(await confirmReopen(deal.stage, stage))
    ) {
      return false;
    }
    let current: Deal | null = deal;
    if (fillRequired && requiredNames(stage).length) {
      current = await fillRequired(deal, stage);
      if (!current) return false;
    }
    // HUB-392: moving into a lost stage asks why first (DL3: unless the pipeline lets it be
    // skipped); a won stage asks an optional won reason.
    const answer: (LostAnswer | WonAnswerWithContract) | null =
      stage.stageType === 'lost'
        ? await lostReason.ask(deal.name, { required: pipeline.lostReasonRequired !== false })
        : stage.stageType === 'won'
          ? await wonReason.ask(deal.name, {
              required: pipeline.wonReasonRequired === true,
              contract: true,
            })
          : {};
    if (!answer) return false;
    // HUB-707 #752: the signed contract is attached after the move, not sent with it.
    const { contract, ...lost } = answer as WonAnswerWithContract & LostAnswer;
    try {
      const move = (from: Deal) =>
        changeDealStage(deal.id, {
          ...lost,
          stageId: stage.id,
          ...(pipeline.id !== deal.pipeline.id ? { pipelineId: pipeline.id } : {}),
          updatedAt: from.updatedAt,
        });
      let updated: Deal;
      try {
        updated = await move(current);
      } catch (err) {
        // Required properties changed meanwhile: ask for the ones the API names, then retry.
        const names = fillRequired ? stageRequirementsOf(err) : null;
        if (!fillRequired || !names) throw err;
        const filled = await fillRequired(await getDeal(deal.id), stage, names);
        if (!filled) return false;
        updated = await move(filled);
      }
      toast(`Moved to ${pipeline.name} · ${stage.name}`);
      if (contract) {
        try {
          await attachContract(deal.id, contract);
          toast('Signed contract attached', 'success');
        } catch (err) {
          toast(
            `The deal is won, but the contract wasn't attached: ${actionErrorText(err)}`,
            'danger',
          );
        }
      }
      onMoved(updated);
    } catch (err) {
      toast(actionErrorText(err), 'danger', { durationMs: 8000 });
      return false;
    }
  };

  return (
    <>
      {lostReason.dialog}
      {wonReason.dialog}
      <FormDrawer
        id="moveDealPipelineDrawer"
        title="Move to pipeline"
        submitLabel="Move"
        open={open}
        onClose={onClose}
        onSubmit={onSubmit}
      >
        <p className="crm-text-body-secondary crm-mb-3">
          Now in <strong>{deal.pipeline.name}</strong> · {deal.stage.name}
        </p>
        <Field label="Pipeline" htmlFor="deal-move-pipeline">
          <select
            id="deal-move-pipeline"
            className="input"
            value={pipelineId}
            disabled={!loaded}
            required
            onChange={(e) => {
              const next = pipelines.find((p) => p.id === e.target.value);
              setPipelineId(e.target.value);
              setStageId(activeStages(next)[0]?.id ?? '');
            }}
          >
            {!loaded ? <option value="">Loading…</option> : null}
            {pipelines.map((p) => (
              <option key={p.id} value={p.id}>
                {p.id === deal.pipeline.id ? `${p.name} (current)` : p.name}
              </option>
            ))}
          </select>
        </Field>
        <Field label="Stage" htmlFor="deal-move-stage">
          <select
            id="deal-move-stage"
            className="input"
            value={stageId}
            disabled={!loaded || stages.length === 0}
            required
            onChange={(e) => setStageId(e.target.value)}
          >
            {stages.map((s) => (
              <option key={s.id} value={s.id}>
                {s.id === deal.stage.id ? `${s.name} (current)` : s.name}
              </option>
            ))}
          </select>
        </Field>
      </FormDrawer>
    </>
  );
}
