'use client';

import { useState, useEffect } from 'react';

interface SystemSettings {
  id: number;
  search_page_size: number;
  korea_margin_percent: number;
  mongolia_margin_percent: number;
  cc_per_usdc: number;
  cc_per_view: number;
  cc_signup_bonus: number;
  cars_per_cc: number;
  cache_ttl_hours: number;
  container_logistics_usd: number;
  shoring_cost_usd: number;
  referral_reward_enabled: boolean;
  referral_reward_percent: number;
  referral_reward_type: string;
  exchange_rate_weight_usd: number;
  exchange_rate_weight_mnt: number;
  exchange_rate_weight_rub: number;
  exchange_rate_weight_cny: number;
}

interface ExchangeRateWeights {
  usd: number;
  mnt: number;
  rub: number;
  cny: number;
}

const API_BASE_URL = process.env.NEXT_PUBLIC_API_URL || 'http://localhost:8000';

export default function SettingsPage() {
  const [settings, setSettings] = useState<SystemSettings | null>(null);
  const [loading, setLoading] = useState(true);
  const [saving, setSaving] = useState(false);
  const [savingExchangeRates, setSavingExchangeRates] = useState(false);
  const [message, setMessage] = useState<{ type: 'success' | 'error'; text: string } | null>(null);
  const [exchangeRateWeights, setExchangeRateWeights] = useState<ExchangeRateWeights>({
    usd: 0,
    mnt: 0,
    rub: 0,
    cny: 0,
  });

  // Form state
  const [formData, setFormData] = useState({
    search_page_size: 20,
    korea_margin_percent: 5.0,
    mongolia_margin_percent: 5.0,
    cc_per_usdc: 1,
    cc_per_view: 1,
    cc_signup_bonus: 3,
    cars_per_cc: 3,
    cache_ttl_hours: 2,
    container_logistics_usd: 3600,
    shoring_cost_usd: 300,
    referral_reward_enabled: true,
    referral_reward_percent: 10.0,
    referral_reward_type: 'one_time',
  });

  useEffect(() => {
    fetchSettings();
    fetchExchangeRateWeights();
  }, []);

  const fetchSettings = async () => {
    try {
      const response = await fetch(`${API_BASE_URL}/api/settings/`);
      if (response.ok) {
        const data = await response.json();
        setSettings(data);
        setFormData({
          search_page_size: data.search_page_size,
          korea_margin_percent: data.korea_margin_percent,
          mongolia_margin_percent: data.mongolia_margin_percent,
          cc_per_usdc: data.cc_per_usdc,
          cc_per_view: data.cc_per_view,
          cc_signup_bonus: data.cc_signup_bonus,
          cars_per_cc: data.cars_per_cc || 3,
          cache_ttl_hours: data.cache_ttl_hours,
          container_logistics_usd: data.container_logistics_usd || 3600,
          shoring_cost_usd: data.shoring_cost_usd || 300,
          referral_reward_enabled: data.referral_reward_enabled ?? true,
          referral_reward_percent: data.referral_reward_percent ?? 10.0,
          referral_reward_type: data.referral_reward_type || 'one_time',
        });
      }
    } catch (error) {
      console.error('Failed to fetch settings:', error);
      setMessage({ type: 'error', text: 'Failed to load settings' });
    } finally {
      setLoading(false);
    }
  };

  const fetchExchangeRateWeights = async () => {
    try {
      const response = await fetch(`${API_BASE_URL}/api/exchange-rate/weights`);
      if (response.ok) {
        const data = await response.json();
        setExchangeRateWeights(data);
      }
    } catch (error) {
      console.error('Failed to fetch exchange rate weights:', error);
    }
  };

  const saveExchangeRateWeights = async () => {
    setSavingExchangeRates(true);
    setMessage(null);

    try {
      const token = localStorage.getItem('token');
      const response = await fetch(`${API_BASE_URL}/api/exchange-rate/weights`, {
        method: 'PUT',
        headers: {
          'Content-Type': 'application/json',
          'Authorization': `Bearer ${token}`,
        },
        body: JSON.stringify(exchangeRateWeights),
      });

      if (response.ok) {
        setMessage({ type: 'success', text: 'Exchange rate weights saved successfully!' });
      } else {
        const error = await response.json();
        setMessage({ type: 'error', text: error.detail || 'Failed to save exchange rate weights' });
      }
    } catch (error) {
      console.error('Failed to save exchange rate weights:', error);
      setMessage({ type: 'error', text: 'Failed to save exchange rate weights' });
    } finally {
      setSavingExchangeRates(false);
    }
  };

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    setSaving(true);
    setMessage(null);

    try {
      const token = localStorage.getItem('token');
      const response = await fetch(`${API_BASE_URL}/api/settings/`, {
        method: 'PUT',
        headers: {
          'Content-Type': 'application/json',
          'Authorization': `Bearer ${token}`,
        },
        body: JSON.stringify(formData),
      });

      if (response.ok) {
        const data = await response.json();
        setSettings(data);
        setMessage({ type: 'success', text: 'Settings saved successfully!' });
      } else {
        const error = await response.json();
        setMessage({ type: 'error', text: error.detail || 'Failed to save settings' });
      }
    } catch (error) {
      console.error('Failed to save settings:', error);
      setMessage({ type: 'error', text: 'Failed to save settings' });
    } finally {
      setSaving(false);
    }
  };

  const handleChange = (field: keyof typeof formData, value: number) => {
    setFormData(prev => ({ ...prev, [field]: value }));
  };

  if (loading) {
    return (
      <div className="flex items-center justify-center h-64">
        <div className="animate-spin rounded-full h-12 w-12 border-b-2 border-primary-600"></div>
      </div>
    );
  }

  return (
    <div className="max-w-4xl">
      <h1 className="text-2xl font-bold text-gray-800 mb-6">System Settings</h1>

      {message && (
        <div className={`mb-6 p-4 rounded-lg ${
          message.type === 'success' ? 'bg-green-100 text-green-700' : 'bg-red-100 text-red-700'
        }`}>
          {message.text}
        </div>
      )}

      <form onSubmit={handleSubmit} className="space-y-6">
        {/* Search Settings */}
        <div className="bg-white rounded-xl shadow-sm p-6">
          <h2 className="text-lg font-semibold text-gray-800 mb-4 flex items-center gap-2">
            <span>Search Settings</span>
          </h2>

          <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
            <div>
              <label className="block text-sm font-medium text-gray-700 mb-1">
                Search Results Per Page
              </label>
              <input
                type="number"
                min="5"
                max="100"
                value={formData.search_page_size}
                onChange={(e) => handleChange('search_page_size', parseInt(e.target.value) || 20)}
                className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-primary-500 focus:border-primary-500"
              />
              <p className="mt-1 text-sm text-gray-500">Number of cars displayed per page in search results (5-100)</p>
            </div>

            <div>
              <label className="block text-sm font-medium text-gray-700 mb-1">
                Cache TTL (Hours)
              </label>
              <input
                type="number"
                min="1"
                max="24"
                value={formData.cache_ttl_hours}
                onChange={(e) => handleChange('cache_ttl_hours', parseInt(e.target.value) || 2)}
                className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-primary-500 focus:border-primary-500"
              />
              <p className="mt-1 text-sm text-gray-500">How long to cache search results (1-24 hours)</p>
            </div>
          </div>
        </div>

        {/* Margin Settings */}
        <div className="bg-white rounded-xl shadow-sm p-6">
          <h2 className="text-lg font-semibold text-gray-800 mb-4 flex items-center gap-2">
            <span>Margin Settings</span>
          </h2>

          <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
            <div>
              <label className="block text-sm font-medium text-gray-700 mb-1">
                Korea Margin (%)
              </label>
              <input
                type="number"
                min="0"
                max="50"
                step="0.1"
                value={formData.korea_margin_percent}
                onChange={(e) => handleChange('korea_margin_percent', parseFloat(e.target.value) || 5)}
                className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-primary-500 focus:border-primary-500"
              />
              <p className="mt-1 text-sm text-gray-500">Margin percentage for Korea sales</p>
            </div>

            <div>
              <label className="block text-sm font-medium text-gray-700 mb-1">
                Mongolia Margin (%)
              </label>
              <input
                type="number"
                min="0"
                max="50"
                step="0.1"
                value={formData.mongolia_margin_percent}
                onChange={(e) => handleChange('mongolia_margin_percent', parseFloat(e.target.value) || 5)}
                className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-primary-500 focus:border-primary-500"
              />
              <p className="mt-1 text-sm text-gray-500">Margin percentage for Mongolia exports</p>
            </div>
          </div>
        </div>

        {/* CC Coin Settings */}
        <div className="bg-white rounded-xl shadow-sm p-6">
          <h2 className="text-lg font-semibold text-gray-800 mb-4 flex items-center gap-2">
            <span>CC Coin Settings</span>
          </h2>

          <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
            <div>
              <label className="block text-sm font-medium text-gray-700 mb-1">
                CC per USD
              </label>
              <input
                type="number"
                min="1"
                max="100"
                value={formData.cc_per_usdc}
                onChange={(e) => handleChange('cc_per_usdc', parseInt(e.target.value) || 10)}
                className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-primary-500 focus:border-primary-500"
              />
              <p className="mt-1 text-sm text-gray-500">1 USD = X CC</p>
            </div>

            <div>
              <label className="block text-sm font-medium text-gray-700 mb-1">
                CC per Request
              </label>
              <input
                type="number"
                min="0"
                max="10"
                value={formData.cc_per_view}
                onChange={(e) => handleChange('cc_per_view', parseInt(e.target.value) || 1)}
                className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-primary-500 focus:border-primary-500"
              />
              <p className="mt-1 text-sm text-gray-500">CC consumed per vehicle request</p>
            </div>

            <div>
              <label className="block text-sm font-medium text-gray-700 mb-1">
                Cars per CC (추천 대수)
              </label>
              <input
                type="number"
                min="1"
                max="50"
                value={formData.cars_per_cc}
                onChange={(e) => handleChange('cars_per_cc', parseInt(e.target.value) || 3)}
                className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-primary-500 focus:border-primary-500"
              />
              <p className="mt-1 text-sm text-gray-500">1 CC = {formData.cars_per_cc} recommended vehicles</p>
            </div>

            <div>
              <label className="block text-sm font-medium text-gray-700 mb-1">
                Signup Bonus CC
              </label>
              <input
                type="number"
                min="0"
                max="100"
                value={formData.cc_signup_bonus}
                onChange={(e) => handleChange('cc_signup_bonus', parseInt(e.target.value) || 3)}
                className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-primary-500 focus:border-primary-500"
              />
              <p className="mt-1 text-sm text-gray-500">Free CC for new users</p>
            </div>
          </div>

          <div className="mt-4 p-4 bg-blue-50 rounded-lg">
            <h3 className="font-medium text-blue-800 mb-2">CC Value Preview</h3>
            <div className="text-sm text-blue-700 space-y-1">
              <p>1 CC = {formData.cars_per_cc} recommended vehicles</p>
              <p>Signup Bonus ({formData.cc_signup_bonus} CC) = {formData.cc_signup_bonus * formData.cars_per_cc} vehicles</p>
            </div>
          </div>
        </div>

        {/* Container Logistics Settings */}
        <div className="bg-white rounded-xl shadow-sm p-6">
          <h2 className="text-lg font-semibold text-gray-800 mb-4 flex items-center gap-2">
            <span>🚢 Container Logistics Settings</span>
          </h2>

          <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
            <div>
              <label className="block text-sm font-medium text-gray-700 mb-1">
                Container Logistics Cost (USD)
              </label>
              <input
                type="number"
                min="0"
                max="10000"
                value={formData.container_logistics_usd}
                onChange={(e) => handleChange('container_logistics_usd', parseInt(e.target.value) || 3600)}
                className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-primary-500 focus:border-primary-500"
              />
              <p className="mt-1 text-sm text-gray-500">컨테이너 물류비 (기본값: $3,600)</p>
            </div>

            <div>
              <label className="block text-sm font-medium text-gray-700 mb-1">
                Shoring Cost (USD)
              </label>
              <input
                type="number"
                min="0"
                max="1000"
                value={formData.shoring_cost_usd}
                onChange={(e) => handleChange('shoring_cost_usd', parseInt(e.target.value) || 300)}
                className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-primary-500 focus:border-primary-500"
              />
              <p className="mt-1 text-sm text-gray-500">쇼링비 - 컨테이너 고정 비용 (기본값: $300)</p>
            </div>
          </div>

          <div className="mt-4 p-4 bg-blue-50 rounded-lg">
            <h3 className="font-medium text-blue-800 mb-2">Cost Calculation Preview</h3>
            <div className="text-sm text-blue-700 space-y-1">
              <p>Total Container Cost: ${formData.container_logistics_usd + formData.shoring_cost_usd}</p>
              <p>Small Car (5.5/10): ${((formData.container_logistics_usd + formData.shoring_cost_usd) * 0.275).toFixed(0)} per car</p>
              <p>Compact Car (4.5/10): ${((formData.container_logistics_usd + formData.shoring_cost_usd) * 0.225).toFixed(0)} per car</p>
            </div>
          </div>
        </div>

        {/* Referral Settings */}
        <div className="bg-white rounded-xl shadow-sm p-6">
          <h2 className="text-lg font-semibold text-gray-800 mb-4 flex items-center gap-2">
            <span>👥 Referral Reward Settings</span>
          </h2>

          <div className="space-y-4">
            <div className="flex items-center gap-3">
              <label className="relative inline-flex items-center cursor-pointer">
                <input
                  type="checkbox"
                  checked={formData.referral_reward_enabled}
                  onChange={(e) => setFormData(prev => ({ ...prev, referral_reward_enabled: e.target.checked }))}
                  className="sr-only peer"
                />
                <div className="w-11 h-6 bg-gray-200 peer-focus:outline-none peer-focus:ring-4 peer-focus:ring-primary-300 rounded-full peer peer-checked:after:translate-x-full rtl:peer-checked:after:-translate-x-full peer-checked:after:border-white after:content-[''] after:absolute after:top-[2px] after:start-[2px] after:bg-white after:border-gray-300 after:border after:rounded-full after:h-5 after:w-5 after:transition-all peer-checked:bg-primary-600"></div>
              </label>
              <span className="text-sm font-medium text-gray-700">Enable Referral Rewards</span>
            </div>

            <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
              <div>
                <label className="block text-sm font-medium text-gray-700 mb-1">
                  Reward Percentage (%)
                </label>
                <input
                  type="number"
                  min="0"
                  max="50"
                  step="0.1"
                  value={formData.referral_reward_percent}
                  onChange={(e) => setFormData(prev => ({ ...prev, referral_reward_percent: parseFloat(e.target.value) || 10 }))}
                  className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-primary-500 focus:border-primary-500"
                />
                <p className="mt-1 text-sm text-gray-500">Percentage of payment given as referral reward</p>
              </div>

              <div>
                <label className="block text-sm font-medium text-gray-700 mb-1">
                  Reward Type
                </label>
                <select
                  value={formData.referral_reward_type}
                  onChange={(e) => setFormData(prev => ({ ...prev, referral_reward_type: e.target.value }))}
                  className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-primary-500 focus:border-primary-500"
                >
                  <option value="one_time">One-time (First payment only)</option>
                  <option value="recurring">Recurring (Every payment)</option>
                </select>
                <p className="mt-1 text-sm text-gray-500">When to give referral rewards</p>
              </div>
            </div>

            <div className="p-4 bg-green-50 rounded-lg">
              <h3 className="font-medium text-green-800 mb-2">Example Calculation</h3>
              <div className="text-sm text-green-700 space-y-1">
                <p>If a referred user charges $100 USD:</p>
                <p>Referrer receives: ${(100 * formData.referral_reward_percent / 100).toFixed(2)} USD</p>
                <p>Type: {formData.referral_reward_type === 'one_time' ? 'Only on first payment' : 'Every time they pay'}</p>
              </div>
            </div>
          </div>
        </div>

        {/* Submit Button */}
        <div className="flex justify-end">
          <button
            type="submit"
            disabled={saving}
            className="px-6 py-2 bg-primary-600 text-white rounded-lg hover:bg-primary-700 disabled:opacity-50 disabled:cursor-not-allowed flex items-center gap-2"
          >
            {saving && (
              <div className="animate-spin rounded-full h-4 w-4 border-b-2 border-white"></div>
            )}
            {saving ? 'Saving...' : 'Save Settings'}
          </button>
        </div>
      </form>

      {/* Exchange Rate Weight Settings - Separate Section */}
      <div className="mt-8 bg-white rounded-xl shadow-sm p-6">
        <h2 className="text-lg font-semibold text-gray-800 mb-4 flex items-center gap-2">
          <span>💱 Exchange Rate Weight Settings</span>
        </h2>

        <p className="text-sm text-gray-600 mb-4">
          환율에 가중치를 적용하여 실제 표시되는 환율을 조정할 수 있습니다. 양수 값은 가격 인상, 음수 값은 가격 인하를 의미합니다.
        </p>

        <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
          <div>
            <label className="block text-sm font-medium text-gray-700 mb-1">
              🇺🇸 USD (미국 달러) Weight (%)
            </label>
            <input
              type="number"
              min="-10"
              max="10"
              step="0.1"
              value={exchangeRateWeights.usd}
              onChange={(e) => setExchangeRateWeights(prev => ({ ...prev, usd: parseFloat(e.target.value) || 0 }))}
              className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-primary-500 focus:border-primary-500"
            />
          </div>

          <div>
            <label className="block text-sm font-medium text-gray-700 mb-1">
              🇲🇳 MNT (몽골 투그릭) Weight (%)
            </label>
            <input
              type="number"
              min="-10"
              max="10"
              step="0.1"
              value={exchangeRateWeights.mnt}
              onChange={(e) => setExchangeRateWeights(prev => ({ ...prev, mnt: parseFloat(e.target.value) || 0 }))}
              className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-primary-500 focus:border-primary-500"
            />
          </div>

          <div>
            <label className="block text-sm font-medium text-gray-700 mb-1">
              🇷🇺 RUB (러시아 루블) Weight (%)
            </label>
            <input
              type="number"
              min="-10"
              max="10"
              step="0.1"
              value={exchangeRateWeights.rub}
              onChange={(e) => setExchangeRateWeights(prev => ({ ...prev, rub: parseFloat(e.target.value) || 0 }))}
              className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-primary-500 focus:border-primary-500"
            />
          </div>

          <div>
            <label className="block text-sm font-medium text-gray-700 mb-1">
              🇨🇳 CNY (중국 위안) Weight (%)
            </label>
            <input
              type="number"
              min="-10"
              max="10"
              step="0.1"
              value={exchangeRateWeights.cny}
              onChange={(e) => setExchangeRateWeights(prev => ({ ...prev, cny: parseFloat(e.target.value) || 0 }))}
              className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-primary-500 focus:border-primary-500"
            />
          </div>
        </div>

        <div className="mt-4 p-4 bg-amber-50 rounded-lg">
          <h3 className="font-medium text-amber-800 mb-2">Weight Preview (예시: +2%)</h3>
          <div className="text-sm text-amber-700 space-y-2">
            <p className="font-medium">예: 기준 환율이 1 USD = 1,400 KRW 일 때</p>
            <div className="bg-white rounded p-3 space-y-1">
              <p>USD 가중치: +2%</p>
              <p>계산식: 1,400 × (1 + 2/100) = 1,400 × 1.0200</p>
              <p className="font-bold text-lg">표시 환율: 1 USD = 1,428 KRW</p>
              <p className="text-xs text-amber-600">(+28 KRW 증가)</p>
            </div>
            <p className="text-xs text-gray-500 mt-2">
              현재 설정된 가중치 - USD: {exchangeRateWeights.usd >= 0 ? '+' : ''}{exchangeRateWeights.usd}%,
              MNT: {exchangeRateWeights.mnt >= 0 ? '+' : ''}{exchangeRateWeights.mnt}%,
              RUB: {exchangeRateWeights.rub >= 0 ? '+' : ''}{exchangeRateWeights.rub}%,
              CNY: {exchangeRateWeights.cny >= 0 ? '+' : ''}{exchangeRateWeights.cny}%
            </p>
          </div>
        </div>

        <div className="mt-4 flex justify-end">
          <button
            type="button"
            onClick={saveExchangeRateWeights}
            disabled={savingExchangeRates}
            className="px-6 py-2 bg-amber-600 text-white rounded-lg hover:bg-amber-700 disabled:opacity-50 disabled:cursor-not-allowed flex items-center gap-2"
          >
            {savingExchangeRates && (
              <div className="animate-spin rounded-full h-4 w-4 border-b-2 border-white"></div>
            )}
            {savingExchangeRates ? 'Saving...' : 'Save Exchange Rate Weights'}
          </button>
        </div>
      </div>
    </div>
  );
}
