import React, { useEffect, useState } from 'react';
import { DollarSign, Save, Info, Globe } from 'lucide-react';
import { toast } from 'react-toastify';
import systemSettingsService, { PlatformCurrencyResponse } from '../../features/system/services/systemSettingsService';
import { useCurrency } from '../../features/payments/contexts/CurrencyContext';
import Loading from '../../shared/components/Loading';
import { getCurrencySymbol } from '../../shared/utils/format';

const CurrencySettingsPage: React.FC = () => {
  const { currency, supportedCurrencies, refreshCurrency } = useCurrency();
  const [selectedCurrency, setSelectedCurrency] = useState<string>(currency);
  const [currencyInfo, setCurrencyInfo] = useState<PlatformCurrencyResponse['data'] | null>(null);
  const [loading, setLoading] = useState(true);
  const [saving, setSaving] = useState(false);

  const currencyNames: Record<string, string> = {
    USD: 'US Dollar',
    EUR: 'Euro',
    GBP: 'British Pound',
    JPY: 'Japanese Yen',
    CNY: 'Chinese Yuan',
    KRW: 'South Korean Won',
    SGD: 'Singapore Dollar',
    THB: 'Thai Baht',
    AUD: 'Australian Dollar',
    CAD: 'Canadian Dollar',
  };

  const getCurrencyDisplayName = (code: string): string => {
    const name = currencyNames[code] || code;
    const symbol = getCurrencySymbol(code);
    return `${name} (${symbol})`;
  };

  const loadCurrencySettings = async () => {
    try {
      setLoading(true);
      const response = await systemSettingsService.getPlatformCurrency();
      setCurrencyInfo(response.data);
      setSelectedCurrency(response.data.currency);
    } catch (error: unknown) {
      toast.error(getUserFriendlyError(error) || 'Failed to load currency settings');
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    void loadCurrencySettings();
  }, []);

  useEffect(() => {
    setSelectedCurrency(currency);
  }, [currency]);

  const handleSave = async () => {
    try {
      setSaving(true);
      await systemSettingsService.updatePlatformCurrency(selectedCurrency);
      await refreshCurrency();
      await loadCurrencySettings();
      toast.success('Platform currency updated successfully');
    } catch (error: unknown) {
      toast.error(getUserFriendlyError(error) || 'Failed to update platform currency');
    } finally {
      setSaving(false);
    }
  };

  if (loading) {
    return <Loading fullScreen={false} text="Loading currency settings..." />;
  }

  return (
    <div className="space-y-10 pb-8 animate-fade-in">
      {}
      <div className="flex flex-col sm:flex-row items-start sm:items-center justify-between gap-6 pb-6 border-b border-gray-200/60">
        <div className="space-y-3">
          <div className="flex items-center gap-3">
            <div className="p-2.5 rounded-lg bg-gradient-to-br from-[var(--luxury-gold)]/10 to-[var(--luxury-gold)]/5 border border-[var(--luxury-gold)]/20 shadow-sm">
              <DollarSign className="w-6 h-6 text-[var(--luxury-gold)]" />
            </div>
            <h1 className="enterprise-section-title">Platform Currency Settings</h1>
          </div>
          <p className="enterprise-section-subtitle max-w-2xl text-gray-600">
            Set the default currency that will be displayed across all dashboards and pages
            throughout the platform. This setting applies to all users.
          </p>
        </div>

        <button
          type="button"
          onClick={handleSave}
          disabled={saving || selectedCurrency === currency}
          className="btn-enterprise-primary inline-flex items-center gap-2 whitespace-nowrap disabled:opacity-50 disabled:cursor-not-allowed"
        >
          <Save className={`w-4 h-4 ${saving ? 'animate-pulse' : ''}`} />
          {saving ? 'Saving...' : 'Save Changes'}
        </button>
      </div>

      {}
      <div className="enterprise-card flex gap-5 p-6 bg-gradient-to-br from-blue-50/50 to-indigo-50/30 border-blue-100/60">
        <div className="mt-0.5 flex-shrink-0">
          <div className="p-2.5 rounded-lg bg-gradient-to-br from-blue-500/10 to-indigo-500/10 border border-blue-200/40">
            <Info className="w-5 h-5 text-blue-600" />
          </div>
        </div>
        <div className="space-y-2.5 flex-1">
          <p className="font-semibold text-gray-900 text-base">
            How platform currency works
          </p>
          <p className="text-sm text-gray-700 leading-relaxed">
            The platform currency you select here will be used to display all prices, amounts,
            and financial information across the entire application. This includes customer-facing
            pages, admin dashboards, reports, and booking pages. All users will see prices in
            the selected currency.
          </p>
          {currencyInfo?.updated_at && (
            <div className="pt-2 border-t border-gray-200/60">
              <p className="text-xs text-gray-500 font-medium">
                Last updated on{' '}
                <span className="text-gray-700">
                  {new Date(currencyInfo.updated_at).toLocaleString(undefined, {
                    dateStyle: 'medium',
                    timeStyle: 'short',
                  })}
                </span>
                {currencyInfo.updated_by && (
                  <>
                    {' '}by <span className="text-gray-700 font-semibold">{currencyInfo.updated_by}</span>
                  </>
                )}
              </p>
            </div>
          )}
        </div>
      </div>

      {}
      <div className="enterprise-card p-6 space-y-6">
        <div className="flex flex-col gap-4 md:flex-row md:items-start md:justify-between pb-4 border-b border-gray-200/60">
          <div className="flex items-start gap-3">
            <div className="p-2 rounded-lg bg-gradient-to-br from-green-500/10 to-emerald-500/10 border border-green-200/40 mt-0.5">
              <Globe className="w-5 h-5 text-green-600" />
            </div>
            <div className="space-y-1.5">
              <p className="font-bold text-gray-900 text-lg">
                Select Platform Currency
              </p>
              <p className="text-sm text-gray-600 leading-relaxed max-w-xl">
                Choose the currency that will be used throughout the platform for displaying
                all monetary values.
              </p>
            </div>
          </div>
        </div>

        <div className="space-y-4">
          <div className="space-y-3">
            <label className="block text-sm font-semibold text-gray-900 tracking-wide">
              Currency
            </label>
            <select
              value={selectedCurrency}
              onChange={(e) => setSelectedCurrency(e.target.value)}
              className="enterprise-input text-sm max-w-md"
            >
              {supportedCurrencies.map((curr) => (
                <option key={curr} value={curr}>
                  {curr} - {getCurrencyDisplayName(curr)}
                </option>
              ))}
            </select>
            <p className="text-xs text-gray-500 leading-relaxed">
              Current platform currency: <span className="font-semibold text-gray-700">{currency}</span>
            </p>
          </div>
        </div>
      </div>
    </div>
  );
};

export default CurrencySettingsPage;

