import { useState } from "react";
import type { CostPreview } from "../../domain/types";
import { useI18n } from "../../i18n/I18nContext";
import { Badge, Button, Input } from "../ui";

type Props = {
  preview: CostPreview;
  onConfirm: (creditCeiling: number) => void;
  onCancel: () => void;
  busy?: boolean;
};

export function CostPreviewDialog({ preview, onConfirm, onCancel, busy = false }: Props) {
  const { t } = useI18n();
  const [ceiling, setCeiling] = useState(String(preview.max_credits));
  const value = Number(ceiling);
  const valid = Number.isFinite(value) && value >= preview.fixed_credits && value <= preview.max_credits;
  return (
    <div className="hb-cost-dialog" role="dialog" aria-modal="true" aria-label={t("radar.cost.aria")}>
      <div className="hb-cost-dialog__head"><div><h3>{t("radar.cost.title")}</h3><p className="hb-radar-section__hint">{t("radar.cost.hint")}</p></div><Badge tone={preview.key_mode === "byok" ? "brand" : "warning"}>{preview.key_mode === "byok" ? t("radar.cost.byok") : t("radar.cost.platform")}</Badge></div>
      <dl className="hb-cost-dialog__stats"><div><dt>{t("radar.cost.fixed")}</dt><dd>{preview.fixed_credits}</dd></div><div><dt>{t("radar.cost.range")}</dt><dd>{preview.min_credits}–{preview.max_credits}</dd></div><div><dt>{t("radar.cost.calls")}</dt><dd>{preview.search_calls}</dd></div><div><dt>{t("radar.cost.remaining")}</dt><dd>{preview.remaining_credits}</dd></div></dl>
      <p className="hb-radar-section__hint">{preview.estimate_basis} · {t("radar.cost.until", { time: new Date(preview.expires_at / 1_000_000).toLocaleTimeString() })}</p>
      <Input name="credit-ceiling" label={t("radar.cost.ceiling")} type="number" min={preview.fixed_credits} max={preview.max_credits} value={ceiling} onChange={(event) => setCeiling(event.target.value)} hint={t("radar.cost.ceilingHint", { min: preview.fixed_credits, max: preview.max_credits })} />
      {!valid ? <p className="hb-banner-error" role="alert">{t("radar.cost.invalid")}</p> : null}
      <div className="hb-cost-dialog__actions"><Button type="button" disabled={!valid || busy} onClick={() => onConfirm(value)}>{busy ? t("radar.cost.starting") : t("radar.cost.confirm")}</Button><Button type="button" variant="ghost" onClick={onCancel}>{t("common.cancel")}</Button></div>
    </div>
  );
}
