"use client";

import {
  fiatCurrencyDisplayName,
  fiatCurrencyFlagEmoji,
  getCryptoRailAssetLabel,
} from "@sdp/types/payment-rails";
import { WalletIcon } from "lucide-react";
import { useMemo } from "react";
import {
  formatCurrencyAmount,
  resolveTotalBalance,
} from "@/app/dashboard/payments/payments-overview.utils";
import { Combobox } from "@/components/ui/combobox";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { useTranslations } from "@/i18n/provider";
import { toRampCryptoToken } from "@/lib/ramps";
import { findWalletBalanceForToken } from "../wallet-options";
import { AmountBalanceReadout } from "./amount-balance-readout";
import { useRampSelection } from "./ramp-selection-context";

export function CurrencyPairSelector() {
  const t = useTranslations();
  const {
    direction,
    fiatCurrencies,
    assetRails,
    wallets,
    walletsLoading,
    selectedWallet,
    showWallet,
    selectedPair,
    amount,
    onAmountChange,
    onAmountBlur,
    onWalletChange,
    onFiatCurrencyChange,
    onAssetRailChange,
  } = useRampSelection();

  const currencyOptions = useMemo(
    () =>
      fiatCurrencies.map((c) => {
        const flag = fiatCurrencyFlagEmoji(c);
        return {
          value: c,
          label: flag === null ? c : `${flag} ${c}`,
          description: fiatCurrencyDisplayName(c),
        };
      }),
    [fiatCurrencies]
  );

  const walletOptions = useMemo(
    () =>
      wallets.map((w) => {
        const total = w.balances ? resolveTotalBalance(w.balances) : null;
        return {
          value: w.walletId,
          label: w.label ?? w.walletId,
          description: total !== null ? formatCurrencyAmount(total) : undefined,
        };
      }),
    [wallets]
  );

  const assetOptions = useMemo(
    () => assetRails.map((rail) => ({ value: rail, label: getCryptoRailAssetLabel(rail) })),
    [assetRails]
  );

  const isOfframp = direction === "offramp";

  const offrampBalance = useMemo<string | null>(() => {
    if (!isOfframp || !selectedWallet) {
      return null;
    }
    const balance = findWalletBalanceForToken(
      selectedWallet,
      toRampCryptoToken(selectedPair.assetRail)
    );
    return balance ? balance.uiAmount : "0";
  }, [isOfframp, selectedWallet, selectedPair.assetRail]);

  const offrampExceeds =
    offrampBalance !== null && amount !== "" && Number(amount) > Number(offrampBalance);

  const fiatCombobox = (
    <Combobox
      label={
        isOfframp ? t("DashboardPayments.ramps.convertTo") : t("DashboardPayments.ramps.currency")
      }
      value={selectedPair.fiatCurrency}
      onChange={(v) => {
        const currency = fiatCurrencies.find((c) => c === v);
        if (currency) onFiatCurrencyChange(currency);
      }}
      options={currencyOptions}
      placeholder={t("DashboardPayments.ramps.selectCurrency")}
      searchPlaceholder={t("DashboardPayments.ramps.searchCurrencies")}
      variant="dialog"
    />
  );

  const assetCombobox = (
    <Combobox
      label={isOfframp ? t("DashboardPayments.asset") : t("DashboardPayments.ramps.convertTo")}
      value={selectedPair.assetRail}
      onChange={(v) => {
        const rail = assetRails.find((r) => r === v);
        if (rail) onAssetRailChange(rail);
      }}
      options={assetOptions}
      placeholder={t("DashboardPayments.ramps.searchAssets")}
      searchable={false}
    />
  );

  return (
    <div className="flex flex-col gap-4">
      <div className="grid items-end gap-4 sm:grid-cols-[minmax(0,1fr)_200px]">
        <div className="flex flex-col gap-2">
          <Label className="text-tertiary" htmlFor={`${direction}-ramp-amount`}>
            {t("DashboardPayments.ramps.amount")}
          </Label>
          <Input
            id={`${direction}-ramp-amount`}
            type="number"
            inputMode="decimal"
            min={isOfframp ? "0" : "1"}
            step={isOfframp ? "any" : "0.01"}
            value={amount}
            onChange={(event) => onAmountChange(event.currentTarget.value)}
            onBlur={onAmountBlur}
            placeholder={isOfframp ? "1.0" : "20.00"}
            size="xl"
            action={
              offrampBalance !== null ? (
                <AmountBalanceReadout
                  available={offrampBalance}
                  assetLabel={getCryptoRailAssetLabel(selectedPair.assetRail)}
                  exceeds={offrampExceeds}
                  onMax={
                    Number(offrampBalance) > 0 ? () => onAmountChange(offrampBalance) : undefined
                  }
                />
              ) : undefined
            }
          />
        </div>
        {isOfframp ? assetCombobox : fiatCombobox}
      </div>

      <div className={showWallet ? "grid gap-4 sm:grid-cols-[minmax(0,1fr)_200px]" : "grid gap-4"}>
        {showWallet ? (
          <Combobox
            label={
              direction === "onramp"
                ? t("DashboardPayments.ramps.destinationWallet")
                : t("DashboardPayments.ramps.sourceWallet")
            }
            value={selectedWallet?.walletId ?? null}
            onChange={onWalletChange}
            options={walletOptions}
            placeholder={
              direction === "onramp"
                ? t("DashboardPayments.ramps.selectDestinationWallet")
                : t("DashboardPayments.ramps.selectSourceWallet")
            }
            searchPlaceholder={t("DashboardPayments.ramps.searchWallets")}
            icon={<WalletIcon className="size-5 shrink-0 text-tertiary" />}
            isLoading={walletsLoading}
          />
        ) : null}
        {isOfframp ? fiatCombobox : assetCombobox}
      </div>
    </div>
  );
}
