'use client';

// HUB-392 (18 Nov design, "Mark deal as closed lost"): moving a deal into a lost stage asks why;
// the notes are optional; both go with the stage move. Used by the board (card dropped on Closed
// Lost), the record page's stage bar and About, Move to pipeline, Create deal and the forecast.
// DL3 (user, 25 Nov 2026; beyond the design):
// - the reasons are the "Closed Lost Reason" / "Closed Won Reason" fields' options, edited in
//   Settings > Properties (GET /deals/close-reasons), not a fixed list;
// - a pipeline can let the lost reason be skipped (`required: false`);
// - moving into a won stage asks the same way ("Mark deal as closed won"), optional unless the
//   pipeline requires a won reason (HUB-707 #752).
import { useCallback, useEffect, useRef, useState } from 'react';
import { Alert } from '@/components/crm/Alert';
import { CrmModal, ModalHeader } from '@/components/crm/FormDrawer';
import { getDealCloseReasons } from '@/features/deals/api.client';
import { MAX_FILE_BYTES, uploadRecordFile } from '@/features/files/api.client';
import {
  DEAL_LOST_REASONS,
  DEAL_WON_REASONS,
  type CloseReasonList,
  type DealLostReason,
} from '@/features/deals/types';
import { cn } from '@/lib/utils/cn';
import { SnippetTextarea } from '@/features/snippets/ui/SnippetTextarea';

/** The lost answer: no reason when the pipeline let it be skipped. */
export type LostAnswer = { lostReason?: DealLostReason; lostNotes?: string };
export type WonAnswer = { wonReason?: string; wonNotes?: string };
/**
 * HUB-707 #752: the won dialog's answer with the signed contract, when one was picked. The file
 * is not part of the stage move: attach it after the move (`attachContract`).
 */
export type WonAnswerWithContract = WonAnswer & { contract?: File };

/** Attaches a signed contract picked in the won dialog to the deal (Attachments card). */
export function attachContract(dealId: string, file: File) {
  return uploadRecordFile({ type: 'deal', id: dealId }, file);
}

type Variant = 'lost' | 'won';

const COPY: Record<
  Variant,
  {
    title: string;
    question: string;
    reason: string;
    notes: string;
    confirm: string;
    missing: string;
  }
> = {
  lost: {
    title: 'Mark deal as closed lost',
    question: 'Why was {name} lost? Loss reasons feed the Deals lost report.',
    reason: 'Closed lost reason',
    notes: 'Closed lost notes',
    confirm: 'Confirm Closed Lost',
    missing: 'Pick a closed lost reason.',
  },
  won: {
    title: 'Mark deal as closed won',
    question: 'Why was {name} won?',
    reason: 'Closed won reason',
    notes: 'Closed won notes',
    confirm: 'Confirm Closed Won',
    missing: 'Pick a closed won reason.',
  },
};

/** The reasons offered when the business's own can't load (the API's defaults). */
const FALLBACK: Record<Variant, CloseReasonList> = {
  lost: { options: DEAL_LOST_REASONS.map((r) => ({ value: r, label: r })), free: false },
  won: { options: DEAL_WON_REASONS.map((r) => ({ value: r, label: r })), free: false },
};

/** The reasons the dialog offers, loaded each time it opens (admins may have edited them). */
function useReasons(variant: Variant, open: boolean): CloseReasonList | null {
  const [list, setList] = useState<CloseReasonList | null>(null);
  useEffect(() => {
    if (!open) return;
    let alive = true;
    setList(null);
    getDealCloseReasons().then(
      (r) => alive && setList(r[variant]),
      // The defaults: the API still checks the reason against the business's field.
      () => alive && setList(FALLBACK[variant]),
    );
    return () => {
      alive = false;
    };
  }, [open, variant]);
  return list;
}

function CloseReasonDialog({
  variant,
  dealName,
  required,
  contract,
  onCancel,
  onConfirm,
}: {
  variant: Variant;
  dealName: string | null;
  required: boolean;
  /** HUB-707 #752: offer a signed contract upload (won, on an existing deal). */
  contract: boolean;
  onCancel: () => void;
  onConfirm: (reason: string | null, notes: string | null, file: File | null) => void;
}) {
  const open = dealName !== null;
  const copy = COPY[variant];
  const id = variant === 'lost' ? 'dealClosedLostModal' : 'dealClosedWonModal';
  const reasonId = variant === 'lost' ? 'dealLostReason' : 'dealWonReason';
  const notesId = variant === 'lost' ? 'dealLostNotes' : 'dealWonNotes';
  const reasons = useReasons(variant, open);
  const [reason, setReason] = useState('');
  const [notes, setNotes] = useState('');
  const [missing, setMissing] = useState(false);
  const [file, setFile] = useState<File | null>(null);
  const [fileError, setFileError] = useState<string | null>(null);
  const [wasOpen, setWasOpen] = useState(open);
  if (open !== wasOpen) {
    setWasOpen(open);
    if (open) {
      setReason('');
      setNotes('');
      setMissing(false);
      setFile(null);
      setFileError(null);
    }
  }

  const submit = () => {
    if (required && !reason.trim()) {
      setMissing(true);
      document.getElementById(reasonId)?.focus();
      return;
    }
    if (fileError) return;
    onConfirm(reason.trim() || null, notes.trim() || null, file);
  };
  // The won dialog says when everything is optional (HUB-707 #752: a pipeline can require it).
  const question =
    variant === 'won' && !required ? `${copy.question} Both fields are optional.` : copy.question;
  const [before, after] = question.split('{name}');

  return (
    <CrmModal id={id} open={open} onClose={onCancel}>
      <form
        noValidate
        onSubmit={(e) => {
          e.preventDefault();
          submit();
        }}
      >
        <ModalHeader id={id} title={copy.title} onClose={onCancel} />
        <div className="modal__body">
          <p className="crm-mb-3">
            {before}
            <strong>{dealName}</strong>
            {after}
          </p>
          {missing ? <Alert tone="danger">{copy.missing}</Alert> : null}
          <div className={cn('field', missing && !reason && 'is-invalid')}>
            <label className="field__label" htmlFor={reasonId}>
              {copy.reason}
              {required ? <span className="crm-text-danger"> *</span> : null}
            </label>
            {reasons?.free ? (
              // A text field takes any reason; the defaults are offered as suggestions.
              <>
                <input
                  className="input"
                  id={reasonId}
                  list={`${reasonId}-options`}
                  maxLength={191}
                  value={reason}
                  required={required}
                  aria-invalid={missing && !reason ? true : undefined}
                  onChange={(e) => {
                    setReason(e.target.value);
                    setMissing(false);
                  }}
                />
                <datalist id={`${reasonId}-options`}>
                  {reasons.options.map((o) => (
                    <option key={o.value} value={o.value} />
                  ))}
                </datalist>
              </>
            ) : (
              <select
                className="input"
                id={reasonId}
                value={reason}
                required={required}
                disabled={!reasons}
                aria-invalid={missing && !reason ? true : undefined}
                onChange={(e) => {
                  setReason(e.target.value);
                  setMissing(false);
                }}
              >
                <option value="">{reasons ? 'Select a reason' : 'Loading reasons…'}</option>
                {(reasons?.options ?? []).map((o) => (
                  <option key={o.value} value={o.value}>
                    {o.label}
                  </option>
                ))}
              </select>
            )}
          </div>
          <div className="field crm-mt-3">
            <label className="field__label" htmlFor={notesId}>
              {copy.notes}
            </label>
            <SnippetTextarea
              className="input"
              id={notesId}
              rows={4}
              maxLength={5000}
              placeholder="Add context for your team (optional)"
              value={notes}
              onChange={(e) => setNotes(e.target.value)}
            />
          </div>
          {variant === 'won' && contract ? (
            <div className={cn('field crm-mt-3', fileError && 'is-invalid')}>
              <label className="field__label" htmlFor="dealWonContract">
                Signed contract
              </label>
              <input
                className="input"
                id="dealWonContract"
                type="file"
                accept=".pdf,application/pdf"
                aria-describedby="dealWonContractHelp"
                onChange={(e) => {
                  const picked = e.target.files?.[0] ?? null;
                  setFile(picked);
                  setFileError(
                    picked && picked.size > MAX_FILE_BYTES
                      ? 'The file is larger than 25 MB.'
                      : picked && !/\.pdf$/i.test(picked.name)
                        ? 'Pick a PDF file.'
                        : null,
                  );
                }}
              />
              <p className="field__help" id="dealWonContractHelp">
                {fileError ?? 'Optional. A PDF, added to the deal\u2019s attachments.'}
              </p>
            </div>
          ) : null}
        </div>
        <div className="modal__footer">
          <button type="submit" className="btn-crm btn-crm--primary">
            {copy.confirm}
          </button>
          {required ? null : (
            // DL3: skip the reason and move anyway.
            <button
              type="button"
              className="btn-crm btn-crm--outline"
              onClick={() => onConfirm(null, null, null)}
            >
              Skip
            </button>
          )}
          <button type="button" className="btn-crm btn-crm--outline" onClick={onCancel}>
            Cancel
          </button>
        </div>
      </form>
    </CrmModal>
  );
}

/** A promise-style close dialog: `ask` opens it; it resolves with the reason and notes, or null. */
type CloseAnswer = { reason: string | null; notes: string | null; file: File | null };

function useCloseReason(variant: Variant) {
  const [dealName, setDealName] = useState<string | null>(null);
  const [required, setRequired] = useState(variant === 'lost');
  const [contract, setContract] = useState(false);
  const resolver = useRef<((answer: CloseAnswer | null) => void) | null>(null);
  const finish = useCallback((answer: CloseAnswer | null) => {
    resolver.current?.(answer);
    resolver.current = null;
    setDealName(null);
  }, []);
  const ask = useCallback(
    (name: string, isRequired: boolean, withContract = false) =>
      new Promise<CloseAnswer | null>((resolve) => {
        resolver.current?.(null);
        resolver.current = resolve;
        setRequired(isRequired);
        setContract(withContract);
        setDealName(name);
      }),
    [],
  );
  const dialog = (
    <CloseReasonDialog
      variant={variant}
      dealName={dealName}
      required={required}
      contract={contract}
      onCancel={() => finish(null)}
      onConfirm={(reason, notes, file) => finish({ reason, notes, file })}
    />
  );
  return { ask, dialog };
}

/**
 * `ask(dealName, { required })` opens the lost dialog and resolves with the answer (no reason
 * when skipped), or null when cancelled. `required` is the pipeline's "Require a closed lost
 * reason" (default on). Render `dialog` once in the view.
 */
export function useClosedLostReason(): {
  ask: (dealName: string, opts?: { required?: boolean }) => Promise<LostAnswer | null>;
  dialog: React.ReactNode;
} {
  const { ask, dialog } = useCloseReason('lost');
  const askLost = useCallback(
    async (name: string, opts?: { required?: boolean }) => {
      const answer = await ask(name, opts?.required !== false);
      if (!answer) return null;
      return {
        ...(answer.reason ? { lostReason: answer.reason } : {}),
        ...(answer.notes ? { lostNotes: answer.notes } : {}),
      };
    },
    [ask],
  );
  return { ask: askLost, dialog };
}

/**
 * DL3: `ask(dealName, { required })` opens the won dialog and resolves with the answer, or null
 * when cancelled. Optional with Skip unless `required`, the pipeline's "Require a closed won
 * reason" (HUB-707 #752, default off). Render `dialog` once in the view.
 */
export function useClosedWonReason(): {
  ask: (
    dealName: string,
    opts?: { required?: boolean; contract?: boolean },
  ) => Promise<WonAnswerWithContract | null>;
  dialog: React.ReactNode;
} {
  const { ask, dialog } = useCloseReason('won');
  const askWon = useCallback(
    async (name: string, opts?: { required?: boolean; contract?: boolean }) => {
      const answer = await ask(name, opts?.required === true, opts?.contract === true);
      if (!answer) return null;
      return {
        ...(answer.reason ? { wonReason: answer.reason } : {}),
        ...(answer.notes ? { wonNotes: answer.notes } : {}),
        ...(answer.file ? { contract: answer.file } : {}),
      };
    },
    [ask],
  );
  return { ask: askWon, dialog };
}
