// DetailAccountWizard — light confirmation modal that flips a *simple* balance
// account to *detailed* entry mode. Issue #215 (Bilan détail par titres #5).
//
// Decision 2026-06-04 (plan-overnight): TOGGLE-ONLY. The wizard does NOT capture
// any titles. It sets `kind='detailed'` and `detailed_since = today` (the
// authoritative pivot date) via `updateBalanceAccount`. Per-security holdings
// are entered at the NEXT normal snapshot — `validateDetailedSnapshot` tolerates
// pre-pivot aggregated lines and requires holdings only at/after the pivot.
//
// Irreversibility: once holdings exist at/after the pivot, the service backstop
// (#212) rejects a `detailed → simple` downgrade with
// `account_kind_detailed_has_holdings`. The UI exposes no "simplify" action, so
// this confirmation makes the one-way nature explicit before committing.
//
// Mirrors the LinkTransfersModal idiom (createPortal overlay, stopPropagation
// inner card, i18n-only copy, WebKitGTK-safe close button).

import { useState } from "react";
import { createPortal } from "react-dom";
import { useTranslation } from "react-i18next";
import { X, Loader2, AlertTriangle } from "lucide-react";
import {
  updateBalanceAccount,
  BalanceServiceError,
} from "../../services/balance.service";
import type { UpdateBalanceAccountInput } from "../../services/balance.service";

/** Local civil-day ISO (YYYY-MM-DD) — matches stored snapshot date format. */
function localISO(d: Date): string {
  const yy = d.getFullYear();
  const mm = String(d.getMonth() + 1).padStart(2, "0");
  const dd = String(d.getDate()).padStart(2, "0");
  return `${yy}-${mm}-${dd}`;
}

/**
 * Pure builder for the toggle payload — exported for unit testing. Produces the
 * exact `updateBalanceAccount` input the wizard commits: flip to detailed and
 * pin the pivot to `today`'s local civil day. `normalizeSnapshotDate` on the
 * service side accepts this YYYY-MM-DD shape verbatim.
 */
export function buildDetailToggleInput(today: Date): UpdateBalanceAccountInput {
  return { kind: "detailed", detailed_since: localISO(today) };
}

export interface DetailAccountWizardProps {
  accountId: number;
  accountName: string;
  onClose: () => void;
  /** Fired after the account was successfully flipped to detailed. */
  onDetailed?: () => void;
}

export default function DetailAccountWizard({
  accountId,
  accountName,
  onClose,
  onDetailed,
}: DetailAccountWizardProps) {
  const { t } = useTranslation();
  const [submitting, setSubmitting] = useState(false);
  const [error, setError] = useState<string | null>(null);

  // Pivot resolved once at render: the local civil day at confirmation time.
  const pivot = localISO(new Date());

  async function handleConfirm() {
    setSubmitting(true);
    setError(null);
    try {
      await updateBalanceAccount(accountId, buildDetailToggleInput(new Date()));
      onDetailed?.();
      onClose();
    } catch (e) {
      if (e instanceof BalanceServiceError) {
        setError(
          t(`balance.detailWizard.errors.${e.code}`, {
            defaultValue: e.message,
          })
        );
      } else {
        setError(e instanceof Error ? e.message : String(e));
      }
      setSubmitting(false);
    }
  }

  return createPortal(
    <div
      className="fixed inset-0 z-50 flex items-center justify-center bg-black/50"
      onClick={onClose}
    >
      <div
        className="bg-[var(--card)] border border-[var(--border)] rounded-xl shadow-xl w-full max-w-lg flex flex-col"
        onClick={(e) => e.stopPropagation()}
      >
        <div className="flex items-center justify-between px-5 py-4 border-b border-[var(--border)]">
          <h2 className="text-lg font-semibold">
            {t("balance.detailWizard.title", { account: accountName })}
          </h2>
          <button
            type="button"
            onClick={onClose}
            className="p-1 rounded hover:bg-[var(--muted)]/40"
            aria-label={t("common.close")}
          >
            <X size={18} />
          </button>
        </div>

        <div className="px-5 py-4 space-y-3 text-sm">
          <p>{t("balance.detailWizard.intro")}</p>

          <ul className="list-disc pl-5 space-y-1.5 text-[var(--muted-foreground)]">
            <li>{t("balance.detailWizard.pointFrozen")}</li>
            <li>{t("balance.detailWizard.pointNextSnapshot")}</li>
            <li>{t("balance.detailWizard.pointPivot", { date: pivot })}</li>
          </ul>

          <div className="flex items-start gap-2 rounded-lg border border-amber-500/30 bg-amber-500/10 px-3 py-2 text-[var(--foreground)]">
            <AlertTriangle
              size={16}
              className="mt-0.5 shrink-0 text-amber-500"
              aria-hidden
            />
            <span>{t("balance.detailWizard.irreversible")}</span>
          </div>

          {error && (
            <div className="text-xs text-[var(--negative)]">{error}</div>
          )}
        </div>

        <div className="px-5 py-3 border-t border-[var(--border)] flex items-center justify-end gap-2">
          <button
            type="button"
            onClick={onClose}
            disabled={submitting}
            className="px-3 py-1.5 text-sm rounded border border-[var(--border)] hover:bg-[var(--muted)]/30 disabled:opacity-50"
          >
            {t("common.cancel")}
          </button>
          <button
            type="button"
            onClick={handleConfirm}
            disabled={submitting}
            className="px-3 py-1.5 text-sm rounded bg-[var(--primary)] text-white disabled:opacity-50 disabled:cursor-not-allowed"
          >
            {submitting ? (
              <span className="flex items-center gap-1.5">
                <Loader2 className="animate-spin" size={14} />
                {t("balance.detailWizard.confirming")}
              </span>
            ) : (
              t("balance.detailWizard.confirm")
            )}
          </button>
        </div>
      </div>
    </div>,
    document.body
  );
}
