'use client';

import { useEffect, useState } from 'react';
import { api } from '@/lib/api';
import { Save, Layout, Globe, Palette, Settings2, Image as ImageIcon, Sparkles } from 'lucide-react';
import { useAuthStore } from '@/store/authStore';
import { useParams } from 'next/navigation';

export default function AdminSettingsPage() {
  const [settings, setSettings] = useState<Record<string, string>>({});
  const [loading, setLoading] = useState(true);
  const [saving, setSaving] = useState(false);
  const [emailTestLoading, setEmailTestLoading] = useState(false);
  const [emailTestTarget, setEmailTestTarget] = useState('');
  const [emailTestResult, setEmailTestResult] = useState('');
  const [emailStatus, setEmailStatus] = useState<{ status: string; lastError: string | null }>({ status: 'NOT_TESTED', lastError: null });
  const [activeTab, setActiveTab] = useState<'GENERAL' | 'THEME' | 'SEO' | 'PROMO' | 'PAYMENT' | 'ADVANCED'>('GENERAL');
  const token = useAuthStore(s => s.token);
  const params = useParams<{ locale?: string }>();
  const locale = params?.locale || 'vi';

  useEffect(() => {
    const fetchSettings = async () => {
      if (!token) return;
      try {
        const res = await api.get('/admin/settings');
        if (res.data && typeof res.data === 'object') {
          setSettings(res.data);
        }
        const emailStatusResponse = await api.get('/admin/settings/email/status');
        setEmailStatus(emailStatusResponse.data);
      } catch (error) {
        console.error(error);
      } finally {
        setLoading(false);
      }
    };
    fetchSettings();
  }, [token]);

  const handleChange = (key: string, value: string) => {
    setSettings(prev => ({ ...prev, [key]: value }));
  };

  const handleSave = async () => {
    if (!token) return;
    setSaving(true);
    try {
      await api.put('/admin/settings', settings);
      alert('Lưu cấu hình thành công!');
      window.location.reload();
    } catch {
      alert('Lỗi khi lưu cấu hình');
    } finally {
      setSaving(false);
    }
  };

  const errorMessage = (error: unknown, fallback: string) => {
    if (typeof error === 'object' && error !== null && 'response' in error) {
      const response = (error as { response?: { data?: { message?: string } } }).response;
      return response?.data?.message || fallback;
    }
    return fallback;
  };

  const testSmtpConnection = async () => {
    setEmailTestLoading(true);
    setEmailTestResult('Đang kiểm tra kết nối SMTP...');
    try {
      const response = await api.post('/admin/settings/email/test-connection');
      setEmailTestResult(response.data?.success ? 'SUCCESS: SMTP kết nối và xác thực thành công.' : `FAILED: ${response.data?.message || response.data?.code || 'Không xác định'}`);
    } catch (error: unknown) {
      setEmailTestResult(`FAILED: ${errorMessage(error, 'Không thể kiểm tra SMTP')}`);
    } finally { setEmailTestLoading(false); }
  };

  const sendTestEmail = async () => {
    setEmailTestLoading(true);
    setEmailTestResult('Đang gửi email thử...');
    try {
      const response = await api.post('/admin/settings/email/send-test', { targetEmail: emailTestTarget || undefined });
      setEmailTestResult(response.data?.success ? 'SUCCESS: Email thử đã được gửi.' : `FAILED: ${response.data?.message || response.data?.code || 'Không xác định'}`);
    } catch (error: unknown) {
      setEmailTestResult(`FAILED: ${errorMessage(error, 'Không thể gửi email thử')}`);
    } finally { setEmailTestLoading(false); }
  };

  if (loading) return <div className="text-gray-500 py-10">Đang tải cấu hình...</div>;

  return (
    <div className="space-y-6 max-w-4xl">
      <div className="rounded-xl border border-amber-500/20 bg-amber-500/10 px-4 py-3 text-sm text-amber-200">
        Cấu hình này sẽ được áp dụng cho toàn bộ site theo ngôn ngữ {locale === 'vi' ? 'Tiếng Việt' : 'English'}.
      </div>
      <div className="flex items-center justify-between">
        <div>
          <h1 className="text-2xl font-bold text-white">Cấu hình Hệ thống</h1>
          <p className="text-gray-500 text-sm mt-1">Quản lý giao diện, thông tin SEO và các cài đặt chung</p>
        </div>
        <button
          onClick={handleSave}
          disabled={saving}
          className="bg-red-500 hover:bg-red-600 text-white px-5 py-2.5 rounded-xl text-sm font-bold flex items-center gap-2 transition-colors disabled:opacity-50"
        >
          <Save className="w-4 h-4" />
          {saving ? 'Đang lưu...' : 'Lưu thay đổi'}
        </button>
      </div>

      <div className="grid grid-cols-1 md:grid-cols-3 gap-6">
        {/* Navigation Sidebar */}
        <div className="col-span-1 space-y-2">
          <button
            onClick={() => setActiveTab('GENERAL')}
            className={`w-full flex items-center gap-3 px-4 py-3 rounded-xl text-sm font-medium text-left transition-colors ${activeTab === 'GENERAL' ? 'bg-red-500/10 text-red-400 border border-red-500/20' : 'text-gray-400 hover:text-white hover:bg-white/5 border border-transparent'}`}
          >
            <Layout className="w-4 h-4" /> Thông tin chung
          </button>
          <button
            onClick={() => setActiveTab('THEME')}
            className={`w-full flex items-center gap-3 px-4 py-3 rounded-xl text-sm font-medium text-left transition-colors ${activeTab === 'THEME' ? 'bg-red-500/10 text-red-400 border border-red-500/20' : 'text-gray-400 hover:text-white hover:bg-white/5 border border-transparent'}`}
          >
            <Palette className="w-4 h-4" /> Giao diện & Màu sắc
          </button>
          <button
            onClick={() => setActiveTab('SEO')}
            className={`w-full flex items-center gap-3 px-4 py-3 rounded-xl text-sm font-medium text-left transition-colors ${activeTab === 'SEO' ? 'bg-red-500/10 text-red-400 border border-red-500/20' : 'text-gray-400 hover:text-white hover:bg-white/5 border border-transparent'}`}
          >
            <Globe className="w-4 h-4" /> SEO & Meta
          </button>
          <button
            onClick={() => setActiveTab('PROMO')}
            className={`w-full flex items-center gap-3 px-4 py-3 rounded-xl text-sm font-medium text-left transition-colors ${activeTab === 'PROMO' ? 'bg-red-500/10 text-red-400 border border-red-500/20' : 'text-gray-400 hover:text-white hover:bg-white/5 border border-transparent'}`}
          >
            <Sparkles className="w-4 h-4" /> Ưu đãi trong tuần
          </button>
          <button
            onClick={() => setActiveTab('PAYMENT')}
            className={`w-full flex items-center gap-3 px-4 py-3 rounded-xl text-sm font-medium text-left transition-colors ${activeTab === 'PAYMENT' ? 'bg-red-500/10 text-red-400 border border-red-500/20' : 'text-gray-400 hover:text-white hover:bg-white/5 border border-transparent'}`}
          >
            <Settings2 className="w-4 h-4" /> Thanh toán
          </button>
          <button
            onClick={() => setActiveTab('ADVANCED')}
            className={`w-full flex items-center gap-3 px-4 py-3 rounded-xl text-sm font-medium text-left transition-colors ${activeTab === 'ADVANCED' ? 'bg-red-500/10 text-red-400 border border-red-500/20' : 'text-gray-400 hover:text-white hover:bg-white/5 border border-transparent'}`}
          >
            <Settings2 className="w-4 h-4" /> Cấu hình nâng cao
          </button>
        </div>

        {/* Form Content */}
        <div className="col-span-2 bg-[#141414] border border-white/5 rounded-2xl p-6 space-y-6">
          {activeTab === 'GENERAL' && (
            <div className="space-y-4 animate-in fade-in duration-300">
              <div className="grid gap-4 md:grid-cols-2 rounded-xl border border-white/10 bg-black/20 p-4">
                <div><label className="block text-sm font-medium text-gray-400 mb-1.5">Tên miền chính</label><input value={settings.siteUrl || ''} onChange={(e) => handleChange('siteUrl', e.target.value)} placeholder="https://shopmmo.com.vn" className="w-full bg-black/50 border border-white/10 rounded-xl px-4 py-2.5 text-white" /></div>
                <div><label className="block text-sm font-medium text-gray-400 mb-1.5">API URL</label><input value={settings.apiUrl || ''} onChange={(e) => handleChange('apiUrl', e.target.value)} placeholder="https://shopmmo.com.vn/api" className="w-full bg-black/50 border border-white/10 rounded-xl px-4 py-2.5 text-white" /></div>
              </div>
              <div>
                <label className="block text-sm font-medium text-gray-400 mb-1.5">Tên Website</label>
                <input
                  type="text"
                  value={settings.siteName || ''}
                  onChange={(e) => handleChange('siteName', e.target.value)}
                  className="w-full bg-black/50 border border-white/10 rounded-xl px-4 py-2.5 text-white focus:outline-none focus:border-red-500/50"
                />
              </div>
              <div>
                <label className="block text-sm font-medium text-gray-400 mb-1.5">Mô tả ngắn (Description)</label>
                <textarea
                  value={settings.siteDescription || ''}
                  onChange={(e) => handleChange('siteDescription', e.target.value)}
                  rows={3}
                  className="w-full bg-black/50 border border-white/10 rounded-xl px-4 py-2.5 text-white focus:outline-none focus:border-red-500/50 resize-none"
                />
              </div>
              <div>
                <label className="block text-sm font-medium text-gray-400 mb-1.5">Email liên hệ hỗ trợ</label>
                <input
                  type="email"
                  value={settings.contactEmail || ''}
                  onChange={(e) => handleChange('contactEmail', e.target.value)}
                  className="w-full bg-black/50 border border-white/10 rounded-xl px-4 py-2.5 text-white focus:outline-none focus:border-red-500/50"
                />
              </div>
            </div>
          )}

          {activeTab === 'THEME' && (
            <div className="space-y-4 animate-in fade-in duration-300">
              <div>
                <label className="block text-sm font-medium text-gray-400 mb-1.5">URL Logo</label>
                <div className="flex gap-3">
                  <div className="flex-1 relative">
                    <ImageIcon className="absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-gray-500" />
                    <input
                      type="text"
                      value={settings.logoUrl || ''}
                      onChange={(e) => handleChange('logoUrl', e.target.value)}
                      placeholder="https://..."
                      className="w-full bg-black/50 border border-white/10 rounded-xl pl-10 pr-4 py-2.5 text-white focus:outline-none focus:border-red-500/50"
                    />
                  </div>
                  {settings.logoUrl && (
                    <div className="w-11 h-11 bg-white rounded-xl overflow-hidden shrink-0 border border-white/10 p-1 flex items-center justify-center">
                      <img src={settings.logoUrl} alt="Logo preview" className="max-w-full max-h-full object-contain" />
                    </div>
                  )}
                </div>
              </div>
              <div>
                <label className="block text-sm font-medium text-gray-400 mb-1.5">Màu chủ đạo (Primary Color)</label>
                <div className="flex gap-3 items-center">
                  <input
                    type="color"
                    value={settings.primaryColor || '#ef4444'}
                    onChange={(e) => handleChange('primaryColor', e.target.value)}
                    className="w-11 h-11 rounded cursor-pointer border-0 p-0 bg-transparent"
                  />
                  <input
                    type="text"
                    value={settings.primaryColor || ''}
                    onChange={(e) => handleChange('primaryColor', e.target.value)}
                    className="w-full bg-black/50 border border-white/10 rounded-xl px-4 py-2.5 text-white uppercase focus:outline-none focus:border-red-500/50"
                  />
                </div>
              </div>
            </div>
          )}

          {activeTab === 'SEO' && (
            <div className="space-y-4 animate-in fade-in duration-300">
              <div>
                <label className="block text-sm font-medium text-gray-400 mb-1.5">Tiêu đề SEO</label>
                <input
                  type="text"
                  value={settings.seoTitle || ''}
                  onChange={(e) => handleChange('seoTitle', e.target.value)}
                  className="w-full bg-black/50 border border-white/10 rounded-xl px-4 py-2.5 text-white focus:outline-none focus:border-red-500/50"
                />
              </div>
              <div>
                <label className="block text-sm font-medium text-gray-400 mb-1.5">Mô tả SEO</label>
                <textarea
                  value={settings.seoDescription || ''}
                  onChange={(e) => handleChange('seoDescription', e.target.value)}
                  rows={3}
                  className="w-full bg-black/50 border border-white/10 rounded-xl px-4 py-2.5 text-white focus:outline-none focus:border-red-500/50 resize-none"
                />
              </div>
              <div>
                <label className="block text-sm font-medium text-gray-400 mb-1.5">Từ khóa</label>
                <input
                  type="text"
                  value={settings.seoKeywords || ''}
                  onChange={(e) => handleChange('seoKeywords', e.target.value)}
                  className="w-full bg-black/50 border border-white/10 rounded-xl px-4 py-2.5 text-white focus:outline-none focus:border-red-500/50"
                />
              </div>
            </div>
          )}

          {activeTab === 'PROMO' && (
            <div className="space-y-5 animate-in fade-in duration-300">
              <div className="rounded-xl border border-violet-400/20 bg-violet-500/5 p-4 text-sm text-violet-100">
                Banner này hiển thị ở đầu trang Mua bán. Nội dung được công khai, không nhập dữ liệu nhạy cảm.
              </div>
              <div>
                <label className="block text-sm font-medium text-gray-400 mb-1.5">Hiển thị ưu đãi trong tuần</label>
                <select value={settings['marketplace.weeklyPromo.enabled'] || 'true'} onChange={(e) => handleChange('marketplace.weeklyPromo.enabled', e.target.value)} className="w-full bg-black/50 border border-white/10 rounded-xl px-4 py-2.5 text-white focus:outline-none focus:border-red-500/50">
                  <option value="true">Bật banner</option><option value="false">Ẩn banner</option>
                </select>
              </div>
              <div>
                <label className="block text-sm font-medium text-gray-400 mb-1.5">Tiêu đề</label>
                <input value={settings['marketplace.weeklyPromo.title'] || ''} onChange={(e) => handleChange('marketplace.weeklyPromo.title', e.target.value)} placeholder="Ưu đãi nổi bật trong tuần" className="w-full bg-black/50 border border-white/10 rounded-xl px-4 py-2.5 text-white focus:outline-none focus:border-red-500/50" />
              </div>
              <div>
                <label className="block text-sm font-medium text-gray-400 mb-1.5">Mô tả ngắn</label>
                <textarea value={settings['marketplace.weeklyPromo.subtitle'] || ''} onChange={(e) => handleChange('marketplace.weeklyPromo.subtitle', e.target.value)} rows={3} className="w-full resize-none bg-black/50 border border-white/10 rounded-xl px-4 py-2.5 text-white focus:outline-none focus:border-red-500/50" />
              </div>
              <div className="grid grid-cols-1 gap-4 sm:grid-cols-2">
                <div><label className="block text-sm font-medium text-gray-400 mb-1.5">Nhãn nút</label><input value={settings['marketplace.weeklyPromo.buttonLabel'] || ''} onChange={(e) => handleChange('marketplace.weeklyPromo.buttonLabel', e.target.value)} placeholder="Xem ưu đãi ngay" className="w-full bg-black/50 border border-white/10 rounded-xl px-4 py-2.5 text-white focus:outline-none focus:border-red-500/50" /></div>
                <div><label className="block text-sm font-medium text-gray-400 mb-1.5">Đường dẫn nút</label><input value={settings['marketplace.weeklyPromo.buttonUrl'] || ''} onChange={(e) => handleChange('marketplace.weeklyPromo.buttonUrl', e.target.value)} placeholder="/search?sort=featured" className="w-full bg-black/50 border border-white/10 rounded-xl px-4 py-2.5 text-white focus:outline-none focus:border-red-500/50" /></div>
              </div>
              <div>
                <label className="block text-sm font-medium text-gray-400 mb-1.5">URL ảnh banner (không bắt buộc)</label>
                <input value={settings['marketplace.weeklyPromo.imageUrl'] || ''} onChange={(e) => handleChange('marketplace.weeklyPromo.imageUrl', e.target.value)} placeholder="https://..." className="w-full bg-black/50 border border-white/10 rounded-xl px-4 py-2.5 text-white focus:outline-none focus:border-red-500/50" />
                <p className="mt-2 text-xs text-gray-500">Nếu để trống, hệ thống dùng nền đồ họa có sẵn. Nên dùng ảnh ngang tỉ lệ khoảng 4:1.</p>
              </div>
            </div>
          )}

          {activeTab === 'PAYMENT' && (
            <>
            <div className="mb-5 rounded-xl border border-amber-400/20 bg-amber-500/5 p-4">
              <h3 className="font-semibold text-amber-100">USDT BEP20</h3>
              <div className="mt-3 grid gap-3 md:grid-cols-2">
                <input value={settings['payment.usdt.walletAddress'] || ''} onChange={(e) => handleChange('payment.usdt.walletAddress', e.target.value)} placeholder="Địa chỉ ví BEP20" className="rounded-xl border border-white/10 bg-black/50 px-4 py-2.5 text-white" />
                <input value={settings['payment.usdt.minimumAmount'] || '10'} onChange={(e) => handleChange('payment.usdt.minimumAmount', e.target.value)} placeholder="Tối thiểu (USDT)" type="number" min="10" className="rounded-xl border border-white/10 bg-black/50 px-4 py-2.5 text-white" />
              </div>
              <label className="mt-3 flex items-center gap-2 text-sm text-gray-300"><input type="checkbox" checked={settings['payment.usdt.enabled'] !== 'false'} onChange={(e) => handleChange('payment.usdt.enabled', e.target.checked ? 'true' : 'false')} /> Cho phép nạp USDT</label>
            </div>
            <div className="space-y-6 animate-in fade-in duration-300">
              <div className="space-y-4">
                <h2 className="text-lg font-semibold text-white">SePay</h2>
                <div className="grid grid-cols-1 gap-4">
                  <div>
                    <label className="block text-sm font-medium text-gray-400 mb-1.5">Kích hoạt SePay</label>
                    <select
                      value={settings['payment.sepay.enabled'] || 'false'}
                      onChange={(e) => handleChange('payment.sepay.enabled', e.target.value)}
                      className="w-full bg-black/50 border border-white/10 rounded-xl px-4 py-2.5 text-white focus:outline-none focus:border-red-500/50"
                    >
                      <option value="true">Bật</option>
                      <option value="false">Tắt</option>
                    </select>
                  </div>
                  <div>
                    <label className="block text-sm font-medium text-gray-400 mb-1.5">URL cổng SePay</label>
                    <input
                      type="text"
                      value={settings['payment.sepay.gatewayUrl'] || ''}
                      onChange={(e) => handleChange('payment.sepay.gatewayUrl', e.target.value)}
                      className="w-full bg-black/50 border border-white/10 rounded-xl px-4 py-2.5 text-white focus:outline-none focus:border-red-500/50"
                    />
                  </div>
                  <div>
                    <label className="block text-sm font-medium text-gray-400 mb-1.5">Secret Key HMAC</label>
                    <input
                      type="password"
                      value={settings['payment.sepay.webhookSecret'] || ''}
                      onChange={(e) => handleChange('payment.sepay.webhookSecret', e.target.value)}
                      placeholder="Nhập Secret Key HMAC từ SePay"
                      autoComplete="new-password"
                      className="w-full bg-black/50 border border-white/10 rounded-xl px-4 py-2.5 text-white focus:outline-none focus:border-red-500/50"
                    />
                    <p className="mt-1 text-xs text-gray-500">Secret được lưu mã hóa và không hiển thị lại đầy đủ.</p>
                  </div>
                  <div>
                    <label className="block text-sm font-medium text-gray-400 mb-1.5">Webhook Callback</label>
                    <input
                      type="text"
                      value={settings['payment.sepay.callbackUrl'] || ''}
                      onChange={(e) => handleChange('payment.sepay.callbackUrl', e.target.value)}
                      className="w-full bg-black/50 border border-white/10 rounded-xl px-4 py-2.5 text-white focus:outline-none focus:border-red-500/50"
                    />
                  </div>
                </div>
                <p className="text-gray-500 text-xs">Cấu hình các tham số SePay để điều khiển provider và xử lý webhook.</p>
              </div>

              <div className="space-y-4">
                <h2 className="text-lg font-semibold text-white">Manual Deposit</h2>
                <div className="grid grid-cols-1 gap-4">
                  <div>
                    <label className="block text-sm font-medium text-gray-400 mb-1.5">Kích hoạt Manual Deposit</label>
                    <select
                      value={settings['payment.manual.enabled'] || 'false'}
                      onChange={(e) => handleChange('payment.manual.enabled', e.target.value)}
                      className="w-full bg-black/50 border border-white/10 rounded-xl px-4 py-2.5 text-white focus:outline-none focus:border-red-500/50"
                    >
                      <option value="true">Bật</option>
                      <option value="false">Tắt</option>
                    </select>
                  </div>
                  <div>
                    <label className="block text-sm font-medium text-gray-400 mb-1.5">Yêu cầu đính kèm</label>
                    <select
                      value={settings['payment.manual.requireAttachment'] || 'false'}
                      onChange={(e) => handleChange('payment.manual.requireAttachment', e.target.value)}
                      className="w-full bg-black/50 border border-white/10 rounded-xl px-4 py-2.5 text-white focus:outline-none focus:border-red-500/50"
                    >
                      <option value="true">Có</option>
                      <option value="false">Không</option>
                    </select>
                  </div>
                  <div>
                    <label className="block text-sm font-medium text-gray-400 mb-1.5">Phê duyệt thủ công</label>
                    <select
                      value={settings['payment.manual.manualApproval'] || 'false'}
                      onChange={(e) => handleChange('payment.manual.manualApproval', e.target.value)}
                      className="w-full bg-black/50 border border-white/10 rounded-xl px-4 py-2.5 text-white focus:outline-none focus:border-red-500/50"
                    >
                      <option value="true">Có</option>
                      <option value="false">Không</option>
                    </select>
                  </div>
                  <div>
                    <label className="block text-sm font-medium text-gray-400 mb-1.5">Danh sách ngân hàng chuyển khoản</label>
                    <textarea
                      value={settings['payment.bankOptions'] || ''}
                      onChange={(e) => handleChange('payment.bankOptions', e.target.value)}
                      rows={3}
                      placeholder="Vietcombank,Techcombank,BIDV,MB Bank,Sacombank"
                      className="w-full bg-black/50 border border-white/10 rounded-xl px-4 py-2.5 text-white focus:outline-none focus:border-red-500/50 resize-none"
                    />
                  </div>
                </div>
                <p className="text-gray-500 text-xs">Nhập danh sách ngân hàng chuyển khoản, cách nhau bởi dấu phẩy. Danh sách này sẽ hiển thị cho người dùng khi nạp tiền.</p>
              </div>

              <div className="space-y-4">
                <div>
                  <h2 className="text-lg font-semibold text-white">Tài khoản nhận tiền</h2>
                  <p className="mt-1 text-xs text-gray-500">Dùng để tạo QR và hiển thị trong phiên nạp tiền. Mã ngân hàng theo chuẩn VietQR, ví dụ MB, VCB, TCB.</p>
                </div>
                <div className="grid grid-cols-1 gap-4 md:grid-cols-2">
                  <div>
                    <label className="mb-1.5 block text-sm font-medium text-gray-400">Mã ngân hàng VietQR</label>
                    <input value={settings['payment.deposit.bankCode'] || ''} onChange={(e) => handleChange('payment.deposit.bankCode', e.target.value.toUpperCase())} placeholder="MB" className="w-full rounded-xl border border-white/10 bg-black/50 px-4 py-2.5 text-white focus:border-red-500/50 focus:outline-none" />
                  </div>
                  <div>
                    <label className="mb-1.5 block text-sm font-medium text-gray-400">Tên ngân hàng</label>
                    <input value={settings['payment.deposit.bankName'] || ''} onChange={(e) => handleChange('payment.deposit.bankName', e.target.value)} placeholder="MB Bank" className="w-full rounded-xl border border-white/10 bg-black/50 px-4 py-2.5 text-white focus:border-red-500/50 focus:outline-none" />
                  </div>
                  <div>
                    <label className="mb-1.5 block text-sm font-medium text-gray-400">Số tài khoản</label>
                    <input value={settings['payment.deposit.accountNumber'] || ''} onChange={(e) => handleChange('payment.deposit.accountNumber', e.target.value.replace(/\s/g, ''))} placeholder="0902851998" className="w-full rounded-xl border border-white/10 bg-black/50 px-4 py-2.5 text-white focus:border-red-500/50 focus:outline-none" />
                  </div>
                  <div>
                    <label className="mb-1.5 block text-sm font-medium text-gray-400">Chủ tài khoản</label>
                    <input value={settings['payment.deposit.accountName'] || ''} onChange={(e) => handleChange('payment.deposit.accountName', e.target.value.toUpperCase())} placeholder="NGUYEN VAN A" className="w-full rounded-xl border border-white/10 bg-black/50 px-4 py-2.5 text-white focus:border-red-500/50 focus:outline-none" />
                  </div>
                </div>
              </div>

              <div className="space-y-4">
                <h2 className="text-lg font-semibold text-white">Tùy chọn chung</h2>
                <div className="grid grid-cols-1 gap-4">
                  <div>
                    <label className="block text-sm font-medium text-gray-400 mb-1.5">URL callback chung</label>
                    <input
                      type="text"
                      value={settings['payment.callbackBaseUrl'] || ''}
                      onChange={(e) => handleChange('payment.callbackBaseUrl', e.target.value)}
                      className="w-full bg-black/50 border border-white/10 rounded-xl px-4 py-2.5 text-white focus:outline-none focus:border-red-500/50"
                    />
                  </div>
                  <div>
                    <label className="block text-sm font-medium text-gray-400 mb-1.5">Bật Auto payment</label>
                    <select
                      value={settings['payment.auto.enabled'] || 'false'}
                      onChange={(e) => handleChange('payment.auto.enabled', e.target.value)}
                      className="w-full bg-black/50 border border-white/10 rounded-xl px-4 py-2.5 text-white focus:outline-none focus:border-red-500/50"
                    >
                      <option value="true">Bật</option>
                      <option value="false">Tắt</option>
                    </select>
                  </div>
                </div>
                <p className="text-gray-500 text-xs">Các thiết lập chung cho callback và tự động thanh toán.</p>
              </div>
            </div>
            </>
          )}

          {activeTab === 'ADVANCED' && (
            <div className="space-y-4 animate-in fade-in duration-300">
              <div className="rounded-xl border border-cyan-400/20 bg-cyan-500/5 p-4 space-y-4">
                <div><h3 className="font-bold text-cyan-200">Email / SMTP</h3><p className="mt-1 text-xs text-gray-400">Dùng để gửi mã OTP xác minh email. Không nhập mật khẩu vào log hoặc source code.</p></div>
                <select value={settings['email.smtp.enabled'] || 'false'} onChange={(e) => handleChange('email.smtp.enabled', e.target.value)} className="w-full bg-black/50 border border-white/10 rounded-xl px-4 py-2.5 text-white"><option value="true">Bật SMTP</option><option value="false">Tắt SMTP</option></select>
                 <div className="grid gap-3 md:grid-cols-2">
                  <input value={settings['email.smtp.host'] || ''} onChange={(e) => handleChange('email.smtp.host', e.target.value)} placeholder="SMTP host" className="w-full bg-black/50 border border-white/10 rounded-xl px-4 py-2.5 text-white" />
                  <input value={settings['email.smtp.port'] || '587'} onChange={(e) => handleChange('email.smtp.port', e.target.value)} placeholder="587" className="w-full bg-black/50 border border-white/10 rounded-xl px-4 py-2.5 text-white" />
                  <input value={settings['email.smtp.username'] || ''} onChange={(e) => handleChange('email.smtp.username', e.target.value)} placeholder="SMTP username" className="w-full bg-black/50 border border-white/10 rounded-xl px-4 py-2.5 text-white" />
                  <input type="password" value={settings['email.smtp.password'] || ''} onChange={(e) => handleChange('email.smtp.password', e.target.value)} placeholder="Mật khẩu SMTP (để trống giữ nguyên)" className="w-full bg-black/50 border border-white/10 rounded-xl px-4 py-2.5 text-white" />
                  <input value={settings['email.smtp.fromName'] || 'SHOPMMO'} onChange={(e) => handleChange('email.smtp.fromName', e.target.value)} placeholder="SHOPMMO" className="w-full bg-black/50 border border-white/10 rounded-xl px-4 py-2.5 text-white" />
                   <input type="email" value={settings['email.smtp.fromEmail'] || 'support@shopmmo.com.vn'} onChange={(e) => handleChange('email.smtp.fromEmail', e.target.value)} placeholder="support@shopmmo.com.vn" className="w-full bg-black/50 border border-white/10 rounded-xl px-4 py-2.5 text-white" />
                   <input value={settings['email.smtp.replyTo'] || 'support@shopmmo.com.vn'} onChange={(e) => handleChange('email.smtp.replyTo', e.target.value)} placeholder="Reply-To" className="w-full bg-black/50 border border-white/10 rounded-xl px-4 py-2.5 text-white" />
                   <input value={settings['email.smtp.connectionTimeout'] || '10000'} onChange={(e) => handleChange('email.smtp.connectionTimeout', e.target.value)} placeholder="Connection timeout (ms)" type="number" min="1000" className="w-full bg-black/50 border border-white/10 rounded-xl px-4 py-2.5 text-white" />
                   <input value={settings['email.smtp.greetingTimeout'] || '10000'} onChange={(e) => handleChange('email.smtp.greetingTimeout', e.target.value)} placeholder="Greeting timeout (ms)" type="number" min="1000" className="w-full bg-black/50 border border-white/10 rounded-xl px-4 py-2.5 text-white" />
                   <input value={settings['email.smtp.socketTimeout'] || '15000'} onChange={(e) => handleChange('email.smtp.socketTimeout', e.target.value)} placeholder="Socket timeout (ms)" type="number" min="1000" className="w-full bg-black/50 border border-white/10 rounded-xl px-4 py-2.5 text-white" />
                 </div>
                 <select value={settings['email.smtp.secure'] || 'false'} onChange={(e) => handleChange('email.smtp.secure', e.target.value)} className="w-full bg-black/50 border border-white/10 rounded-xl px-4 py-2.5 text-white"><option value="false">TLS STARTTLS (587)</option><option value="true">TLS trực tiếp (465)</option></select>
                 <div className="flex flex-wrap gap-2">
                   <button type="button" onClick={() => void testSmtpConnection()} disabled={emailTestLoading} className="rounded-lg border border-cyan-400/40 px-3 py-2 text-sm font-bold text-cyan-200 disabled:opacity-50">Test SMTP Connection</button>
                   <input value={emailTestTarget} onChange={(e) => setEmailTestTarget(e.target.value)} placeholder="Email nhận test (để trống dùng email admin)" className="min-w-[260px] flex-1 rounded-lg border border-white/10 bg-black/30 px-3 py-2 text-sm text-white" />
                   <button type="button" onClick={() => void sendTestEmail()} disabled={emailTestLoading} className="rounded-lg border border-green-400/40 px-3 py-2 text-sm font-bold text-green-200 disabled:opacity-50">Send Test Email</button>
                 </div>
                 {emailTestResult && <p className={`text-sm ${emailTestResult.startsWith('SUCCESS') ? 'text-green-300' : emailTestResult.startsWith('FAILED') ? 'text-red-300' : 'text-amber-200'}`}>{emailTestResult}</p>}
                 <div className="rounded-lg border border-white/10 bg-black/20 p-3 text-sm"><p className="text-gray-300">SMTP Status: <span className={emailStatus.status === 'SENT' || emailStatus.status === 'SUCCESS' ? 'text-green-300' : emailStatus.status === 'FAILED' ? 'text-red-300' : 'text-amber-200'}>{emailStatus.status}</span></p>{emailStatus.lastError && <p className="mt-1 text-red-300">Last Error: {emailStatus.lastError}</p>}</div>
              </div>
              <div>
                <label className="block text-sm font-medium text-gray-400 mb-1.5">Chế độ bảo trì</label>
                <select
                  value={settings.maintenanceMode || 'false'}
                  onChange={(e) => handleChange('maintenanceMode', e.target.value)}
                  className="w-full bg-black/50 border border-white/10 rounded-xl px-4 py-2.5 text-white focus:outline-none focus:border-red-500/50"
                >
                  <option value="true">Bật</option>
                  <option value="false">Tắt</option>
                </select>
              </div>
              <div>
                <label className="block text-sm font-medium text-gray-400 mb-1.5">Cho phép đăng ký</label>
                <select
                  value={settings.allowRegistration || 'true'}
                  onChange={(e) => handleChange('allowRegistration', e.target.value)}
                  className="w-full bg-black/50 border border-white/10 rounded-xl px-4 py-2.5 text-white focus:outline-none focus:border-red-500/50"
                >
                  <option value="true">Có</option>
                  <option value="false">Không</option>
                </select>
              </div>
            </div>
          )}
        </div>
      </div>
    </div>
  );
}
