// Copyright: © 2026 TWWIM UG. All rights reserved. (www.twwim.com)
/**
 * Read-only display + edit flow for the company's billing currency.
 *
 * UNLOCKED state (no paid payment yet):
 *   • Dropdown lets the owner switch EUR↔USD.
 *   • Submit posts PUT /companies/:id/currency — server rejects with 409 if
 *     the lock was just set by a concurrent payment.
 *
 * LOCKED state (currency_locked_at != null):
 *   • Read-only display + lock badge + hint "cancel to change".
 *
 * Mounted on both /dashboard/profile (PERSONAL accounts) and
 * /dashboard/company (BUSINESS accounts) — a PERSONAL account's "company"
 * row is a shadow over the user themselves, so the same section serves
 * both UX paths without duplication.
 */

import { useState } from 'react';
import { CircleDollarSign, Lock, Check, Loader2 } from 'lucide-react';
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
import { useTranslation } from '@/i18n/TranslationProvider';
import { companiesApi } from '@/infrastructure/http/api/company';
import { queryKeys } from '@/lib/query-keys';
import { Currency, SUPPORTED_CURRENCIES } from '@archer/domain';
import { useAuthenticatedUser } from '@/features/auth/hooks/useAuthenticatedUser';
import { forceTokenRefresh } from '@/infrastructure/http/auth-refresh';

/** Humanized labels keyed off the domain Currency enum — single source of truth. */
const CURRENCY_LABEL: Record<Currency, string> = {
  [Currency.EUR]: '€ Euro',
  [Currency.USD]: '$ US Dollar',
};

export function BillingCurrencySection() {
  const { t } = useTranslation();
  const queryClient = useQueryClient();
  const authed = useAuthenticatedUser();
  const companyId = authed?.companyId;

  const { data: company, isLoading } = useQuery({
    queryKey: queryKeys.companies.detail(companyId ?? ''),
    queryFn: () => companiesApi.getCompany(companyId!),
    enabled: !!companyId,
  });

  const mutation = useMutation({
    mutationFn: (currency: Currency) => companiesApi.updateCurrency(companyId!, currency),
    onSuccess: async () => {
      queryClient.invalidateQueries({ queryKey: queryKeys.companies.all });
      queryClient.invalidateQueries({ queryKey: queryKeys.profile.all });
      // Currency drives plan-selection modal pricing + price formatter. Round-
      // trip the JWT so the AuthenticatedUser snapshot rebuilds from server.
      try { await forceTokenRefresh(); } catch { /* refresh failure: snapshot keeps prior currency until next /auth/me */ }
    },
  });

  const currentCurrency = company?.preferredCurrency ?? null;
  const locked = company?.isCurrencyLocked() ?? false;
  const [draft, setDraft] = useState<Currency | ''>('');

  if (!companyId) return null;

  const handleSave = () => {
    if (draft && draft !== currentCurrency) {
      mutation.mutate(draft);
    }
  };

  return (
    <div className="bg-card rounded-xl border border-border p-6 shadow-sm">
      <div className="flex items-center justify-between mb-2">
        <h2 className="text-lg font-semibold text-foreground flex items-center gap-2">
          <CircleDollarSign className="h-5 w-5 text-muted-foreground" />
          {t('profile.billingCurrency') || 'Billing currency'}
        </h2>
        {locked && (
          <span
            className="inline-flex items-center gap-1 rounded-full bg-amber-50 px-2.5 py-1 text-xs font-semibold text-amber-800"
            title={t('profile.currencyLockedHint') || 'Locked after first paid payment'}
          >
            <Lock className="h-3 w-3" />
            {t('profile.locked') || 'Locked'}
          </span>
        )}
      </div>

      {isLoading ? (
        <p className="text-sm text-muted-foreground">…</p>
      ) : locked ? (
        <>
          <p className="text-base font-medium text-foreground">
            {currentCurrency ? (CURRENCY_LABEL[currentCurrency as Currency] ?? currentCurrency) : '—'}
          </p>
          <p className="mt-1 text-xs text-muted-foreground">
            {t('profile.currencyLockedBody') || 'Your billing currency is locked for the active subscription. Cancel the subscription to change it.'}
          </p>
        </>
      ) : (
        <>
          <div className="flex items-center gap-2">
            <select
              value={draft || currentCurrency || ''}
              onChange={(e) => setDraft(e.target.value as Currency)}
              disabled={mutation.isPending}
              className="flex-1 px-3 py-2.5 border border-border rounded-lg bg-background text-foreground"
            >
              <option value="" disabled>
                {t('profile.currencySelect') || 'Select currency'}
              </option>
              {SUPPORTED_CURRENCIES.map((c) => (
                <option key={c} value={c}>{CURRENCY_LABEL[c]}</option>
              ))}
            </select>
            <button
              type="button"
              onClick={handleSave}
              disabled={mutation.isPending || !draft || draft === currentCurrency}
              className="px-3 py-2.5 text-sm font-medium rounded-lg bg-primary text-primary-foreground hover:bg-primary/90 disabled:opacity-50 inline-flex items-center gap-1.5"
            >
              {mutation.isPending ? <Loader2 className="h-4 w-4 animate-spin" /> : <Check className="h-4 w-4" />}
              {t('common.save') || 'Save'}
            </button>
          </div>
          <p className="mt-1 text-xs text-muted-foreground">
            {t('profile.currencyUnlockedBody') || 'Your billing currency. Locks automatically after your first paid payment.'}
          </p>
          {mutation.isError && (
            <p className="mt-1 text-xs text-destructive">
              {(mutation.error as Error).message || t('profile.currencyChangeFailed') || 'Could not change currency.'}
            </p>
          )}
          {mutation.isSuccess && (
            <p className="mt-1 text-xs text-green-600">
              {t('profile.currencyChanged') || 'Currency updated.'}
            </p>
          )}
        </>
      )}
    </div>
  );
}
