'use client';

import { useLocalization } from '@akinon/next/hooks';
import { useState } from 'react';
import settings from 'settings';
import { Button } from './button';
import { Modal } from './modal';
import { Select } from './select';

interface CurrencySelectProps {
  className?: string;
  showIcon?: boolean;
  /** Custom SVG icon content */
  customIcon?: string;
  /** Label format: 'full' (US Dollar), 'symbol' ($), 'code' (USD) */
  labelFormat?: 'full' | 'symbol' | 'code';
}

export const CurrencySelect = (props: CurrencySelectProps) => {
  const [isModalOpen, setIsModalOpen] = useState(false);
  const [selectedCurrency, setSelectedCurrency] = useState('');
  const { t, currency, setCurrency } = useLocalization();
  const { currencies } = settings.localization;

  // Currency symbol map for common currencies
  const currencySymbolMap: Record<string, string> = {
    usd: '$',
    eur: '€',
    gbp: '£',
    try: '₺',
    jpy: '¥',
    cny: '¥',
    krw: '₩',
    inr: '₹',
    rub: '₽',
    brl: 'R$',
    aud: 'A$',
    cad: 'C$',
    chf: 'CHF',
    sek: 'kr',
    nok: 'kr',
    dkk: 'kr',
    pln: 'zł',
    mxn: '$',
    sgd: 'S$',
    hkd: 'HK$',
    nzd: 'NZ$',
    zar: 'R',
    aed: 'د.إ',
    sar: '﷼',
    thb: '฿',
    myr: 'RM',
    php: '₱',
    idr: 'Rp',
    vnd: '₫',
    egp: 'E£',
    ngn: '₦',
    pkr: '₨',
    bdt: '৳',
    cop: '$',
    ars: '$',
    clp: '$',
    pen: 'S/',
    ils: '₪',
    kwd: 'د.ك',
    qar: '﷼',
    bhd: '.د.ب',
    omr: '﷼'
  };

  // Currency full name map for common currencies
  const currencyNameMap: Record<string, string> = {
    usd: 'US Dollar',
    eur: 'Euro',
    gbp: 'British Pound',
    try: 'Turkish Lira',
    jpy: 'Japanese Yen',
    cny: 'Chinese Yuan',
    krw: 'South Korean Won',
    inr: 'Indian Rupee',
    rub: 'Russian Ruble',
    brl: 'Brazilian Real',
    aud: 'Australian Dollar',
    cad: 'Canadian Dollar',
    chf: 'Swiss Franc',
    sek: 'Swedish Krona',
    nok: 'Norwegian Krone',
    dkk: 'Danish Krone',
    pln: 'Polish Zloty',
    mxn: 'Mexican Peso',
    sgd: 'Singapore Dollar',
    hkd: 'Hong Kong Dollar',
    nzd: 'New Zealand Dollar',
    zar: 'South African Rand',
    aed: 'UAE Dirham',
    sar: 'Saudi Riyal',
    thb: 'Thai Baht',
    myr: 'Malaysian Ringgit',
    php: 'Philippine Peso',
    idr: 'Indonesian Rupiah',
    vnd: 'Vietnamese Dong',
    egp: 'Egyptian Pound',
    ngn: 'Nigerian Naira',
    pkr: 'Pakistani Rupee',
    bdt: 'Bangladeshi Taka',
    cop: 'Colombian Peso',
    ars: 'Argentine Peso',
    clp: 'Chilean Peso',
    pen: 'Peruvian Sol',
    ils: 'Israeli Shekel',
    kwd: 'Kuwaiti Dinar',
    qar: 'Qatari Riyal',
    bhd: 'Bahraini Dinar',
    omr: 'Omani Rial'
  };

  const handleChange = async (e) => {
    setSelectedCurrency(e.currentTarget.value);
    setIsModalOpen(true);
  };

  const confirmModalHandleClick = () => {
    setCurrency(selectedCurrency);
  };

  // Get currency symbol from map or use provided symbol
  const getCurrencySymbol = (curr: { code: string; symbol?: string }) => {
    if (curr.symbol) return curr.symbol;
    return (
      currencySymbolMap[curr.code.toLowerCase()] || curr.code.toUpperCase()
    );
  };

  // Get currency full name from map or use provided label
  const getCurrencyName = (curr: { code: string; label: string }) => {
    const name = currencyNameMap[curr.code.toLowerCase()];
    // If name exists in map, use it. Otherwise check if label looks like a full name (not just code)
    if (name) return name;
    // If label is different from code, assume it's a proper name
    if (curr.label.toLowerCase() !== curr.code.toLowerCase()) return curr.label;
    // Fallback to code uppercase
    return curr.code.toUpperCase();
  };

  // Format label based on labelFormat prop
  const formatLabel = (curr: {
    code: string;
    label: string;
    symbol?: string;
  }) => {
    switch (props.labelFormat) {
      case 'symbol':
        // Return currency symbol ($, €, etc.)
        return getCurrencySymbol(curr);
      case 'code':
        // Return currency code (USD, EUR, etc.)
        return curr.code.toUpperCase();
      case 'full':
      default:
        // Return full label (US Dollar, Euro, etc.)
        return getCurrencyName(curr);
    }
  };

  // Check if customIcon has actual SVG content
  const hasValidCustomIcon =
    props.customIcon &&
    typeof props.customIcon === 'string' &&
    props.customIcon.includes('<svg');

  return (
    <>
      <Select
        onChange={handleChange}
        options={currencies.map((curr) => ({
          value: curr.code,
          label: formatLabel(curr)
        }))}
        value={currency}
        icon={
          props.showIcon !== false && !hasValidCustomIcon ? 'money' : undefined
        }
        customIcon={props.showIcon !== false ? props.customIcon : undefined}
        data-testid="currency"
        borderless
        className={props.className}
      />

      <Modal
        portalId="currency-modal"
        open={isModalOpen}
        setOpen={setIsModalOpen}
      >
        <div className="p-6">
          <h3
            className="text-2xl font-bold text-center mb-4"
            data-testid="currency-modal-title"
          >
            {t('common.currency_modal.title')}
          </h3>
          <p className="text-center mb-10">
            {t('common.currency_modal.description')}
          </p>

          <div className="flex justify-center gap-x-6 my-6">
            <Button
              onClick={() => setIsModalOpen(false)}
              appearance="outlined"
              className="font-medium px-10 py-2 h-12"
            >
              {t('common.currency_modal.close')}
            </Button>

            <Button
              onClick={confirmModalHandleClick}
              appearance="filled"
              className="font-medium px-10 py-4 h-12"
              data-testid="currency-modal-confirm"
            >
              {t('common.currency_modal.continue')}
            </Button>
          </div>
        </div>
      </Modal>
    </>
  );
};
