'use client';

/**
 * DevPaymentsPanel — dev-only panel to control the active mock payment scenario.
 *
 * Sets the `md_mock_scenario` cookie so that <PaymentForm> (and MockCardForm) pick
 * up the scenario on the next checkout attempt.
 *
 * Only rendered when PAYMENT_PROVIDER=mock (the Astro page gates on this).
 */

import { useCallback, useEffect, useId, useState } from 'react';
import { useT } from '@/lib/i18n/react';
import { RadioGroup, RadioItem } from '@/components/ui/primitives/RadioGroup/RadioGroup';
import { InlineNotice } from '@/components/ui/feedback/InlineNotice';
import {
  MOCK_SCENARIOS,
  isMockScenario,
  type MockScenario,
} from '@/server/payments/mock/scenarios';

// ─── Component ────────────────────────────────────────────────────────────────

/**
 * Panel to set the active mock payment scenario via the `md_mock_scenario` cookie.
 *
 * @example
 * ```astro
 * <DevPaymentsPanel client:load />
 * ```
 */
export function DevPaymentsPanel() {
  const t = useT('dev_payments');
  const groupId = useId();

  // Read current scenario from cookie post-mount (SSR safe — useEffect).
  const [scenario, setScenario] = useState<MockScenario>('success');
  const [saved, setSaved] = useState(false);

  useEffect(() => {
    const match = document.cookie.match(/(?:^|;\s*)md_mock_scenario=([^;]+)/);
    const raw = match?.[1] ?? null;
    if (isMockScenario(raw)) {
      void Promise.resolve().then(() => setScenario(raw));
    }
  }, []);

  const handleChange = useCallback((value: string) => {
    if (!isMockScenario(value)) return;
    setScenario(value);
    document.cookie = `md_mock_scenario=${value}; path=/`;
    setSaved(true);
    // Auto-clear the "saved" notice after 2 s.
    setTimeout(() => setSaved(false), 2000);
  }, []);

  // Map each scenario to its i18n label via typed keys.
  const scenarioLabels: Record<MockScenario, string> = {
    success: t('scenario_success'),
    decline: t('scenario_decline'),
    insufficient_funds: t('scenario_insufficient_funds'),
    token_expired: t('scenario_token_expired'),
    token_invalid: t('scenario_token_invalid'),
    duplicate: t('scenario_duplicate'),
    hold_reject_debit: t('scenario_hold_reject_debit'),
    partial_refund_failure: t('scenario_partial_refund_failure'),
    reconcile_flip: t('scenario_reconcile_flip'),
  };

  return (
    <div className="flex flex-col gap-6 p-4">
      <div className="flex flex-col gap-1">
        <h1 className="text-text-primary text-lg font-semibold">{t('page_title')}</h1>
        <p className="text-text-secondary text-sm">{t('page_description')}</p>
      </div>

      <InlineNotice tone="warning" description={t('mock_only_notice')} />

      {saved && <InlineNotice tone="success" description={t('scenario_applied')} />}

      <fieldset className="flex flex-col gap-2">
        <legend className="text-text-primary mb-2 text-sm font-medium">
          {t('scenario_label')}
        </legend>
        <RadioGroup value={scenario} onValueChange={handleChange} aria-label={t('scenario_label')}>
          {MOCK_SCENARIOS.map((s) => {
            const itemId = `${groupId}-${s}`;
            return <RadioItem key={s} id={itemId} value={s} label={scenarioLabels[s]} />;
          })}
        </RadioGroup>
      </fieldset>

      <p className="text-text-muted text-xs">
        {t('active_scenario')}: <strong className="text-text-primary">{scenario}</strong>
      </p>
    </div>
  );
}
