"use client";
import { useEffect, useState } from "react";
import { Button, Field, Input, Select, Sheet, api, useAction } from "./ui";

export type Stage = { id: string; name: string; order: number; probability: number; kind?: "open" | "won" | "lost" };

export const LOST_REASONS = ["Budget mismatch", "Bought elsewhere", "Location not suitable", "Not reachable", "Timeline too long", "Financing not approved", "Just browsing", "Other"];

/**
 * LEAD-007: moving to Lost requires a reason; Won requires a value.
 * Opens a sheet when extra input is needed, otherwise moves immediately.
 */
export function useStageMover(onMoved: () => void) {
  const [pending, setPending] = useState<{ dealId: string; stage: Stage; value: number; position?: number } | null>(null);
  const { busy, run } = useAction();
  const move = async (dealId: string, stage: Stage, currentValue: number, position?: number) => {
    const kind = stage.kind ?? (/won|booked/i.test(stage.name) ? "won" : /lost/i.test(stage.name) ? "lost" : "open");
    if (kind === "lost" || (kind === "won" && !(currentValue > 0)) || kind === "won") {
      setPending({ dealId, stage: { ...stage, kind }, value: currentValue, position });
      return false;
    }
    const r = await run(() => api(`/deals/${dealId}/stage`, { body: { stage_id: stage.id, position } }));
    if (r) onMoved();
    return !!r;
  };
  const sheet = <StageSheet pending={pending} busy={busy} onCancel={() => { setPending(null); onMoved(); }} onConfirm={async (extra) => {
    if (!pending) return;
    const r = await run(() => api(`/deals/${pending.dealId}/stage`, { body: { stage_id: pending.stage.id, position: pending.position, ...extra } }), pending.stage.kind === "won" ? "Deal won 🎉" : "Deal updated");
    if (r) { setPending(null); onMoved(); }
  }} />;
  return { move, sheet };
}

function StageSheet({ pending, busy, onCancel, onConfirm }: { pending: { stage: Stage; value: number } | null; busy: boolean; onCancel: () => void; onConfirm: (x: { lost_reason?: string; value?: number }) => void }) {
  const [reason, setReason] = useState("");
  const [other, setOther] = useState("");
  const [value, setValue] = useState("");
  useEffect(() => { setReason(""); setOther(""); setValue(pending?.value ? String(pending.value / 100) : ""); }, [pending]);
  const won = pending?.stage.kind === "won";
  return (
    <Sheet open={!!pending} onClose={onCancel} width={420} title={won ? "Mark as won" : "Mark as lost"}
      footer={<><Button onClick={onCancel}>Cancel</Button><Button variant={won ? "primary" : "danger"} loading={busy} onClick={() => won ? onConfirm({ value: Math.round(Number(value) * 100) }) : onConfirm({ lost_reason: reason === "Other" ? other : reason })} disabled={won ? !(Number(value) > 0) : !(reason && (reason !== "Other" || other.trim()))}>{won ? "Confirm win" : "Mark lost"}</Button></>}>
      {won ? (
        <Field label="Won value" hint="Required — sent to ad platforms as the conversion value"><Input type="number" min="1" autoFocus value={value} onChange={(e) => setValue(e.target.value)} placeholder="e.g. 18500000" /></Field>
      ) : (
        <div className="space-y-3">
          <Field label="Lost reason" hint="Required — used in loss analysis"><Select value={reason} onChange={(e) => setReason(e.target.value)}><option value="">Choose a reason…</option>{LOST_REASONS.map((r) => <option key={r}>{r}</option>)}</Select></Field>
          {reason === "Other" && <Field label="Describe"><Input autoFocus value={other} onChange={(e) => setOther(e.target.value)} /></Field>}
        </div>
      )}
    </Sheet>
  );
}
