'use client';

import {
  User, Mail, MapPin, Lock, Shield, Bell, Zap, Trash2, ChevronRight,
  Loader2, AlertCircle, ArrowLeft, Upload, X
} from 'lucide-react';
import Link from 'next/link';
import { useState, useEffect, useRef } from 'react';
import { useAuthStore } from '@/store/authStore';
import { api } from '@/lib/api';
import Navbar from '@/components/Navbar';
import { Toaster, toast } from 'react-hot-toast';

export default function EditProfilePage() {
  const user = useAuthStore((s) => s.user);
  const logout = useAuthStore((s) => s.logout);
  const [loading, setLoading] = useState(true);
  const [saving, setSaving] = useState(false);
  const [showPasswordModal, setShowPasswordModal] = useState(false);
  const [show2faModal, setShow2faModal] = useState(false);
  const [showDeleteModal, setShowDeleteModal] = useState(false);
  const [deleting, setDeleting] = useState(false);
  const [activeSection, setActiveSection] = useState<'basic' | 'security' | 'notifications' | 'privacy'>('basic');
  const [emailNotifications, setEmailNotifications] = useState(true);
  const [pushNotifications, setPushNotifications] = useState(false);
  const [publicProfile, setPublicProfile] = useState(true);
  const [profile, setProfile] = useState({
    name: '',
    email: '',
    phone: '',
    address: '',
    city: '',
    district: '',
    ward: '',
    facebookUrl: '',
    discordUrl: '',
    youtubeUrl: '',
    telegramUrl: '',
  });
  const [errors, setErrors] = useState<{ [key: string]: string }>({});

  // Password change state
  const [passwords, setPasswords] = useState({
    currentPassword: '',
    newPassword: '',
    confirmPassword: '',
  });
  const [passwordErrors, setPasswordErrors] = useState<{ [key: string]: string }>({});
  const [passwordLoading, setPasswordLoading] = useState(false);

  // 2FA state
  const [twoFASecret, setTwoFASecret] = useState('');
  const [twoFACode, setTwoFACode] = useState('');
  const [twoFALoading, setTwoFALoading] = useState(false);
  const [isTwoFAEnabled, setIsTwoFAEnabled] = useState(false);
  const [isEmailVerified, setIsEmailVerified] = useState(false);
  const [verificationEmail, setVerificationEmail] = useState('');
  const [verificationCode, setVerificationCode] = useState('');
  const [emailChallenge, setEmailChallenge] = useState<{ id: string; maskedEmail: string; expiresAt: string; resendAvailableAt: string } | null>(null);
  const [emailVerificationLoading, setEmailVerificationLoading] = useState(false);

  // Fetch profile data on mount
  useEffect(() => {
    const fetchProfile = async () => {
      try {
        setLoading(true);
        const response = await api.get('/auth/profile');
        setProfile({
          name: response.data.name || '',
          email: response.data.email || '',
          phone: response.data.phone || '',
          address: response.data.address || '',
          city: response.data.city || '',
          district: response.data.district || '',
          ward: response.data.ward || '',
          facebookUrl: response.data.facebookUrl || '',
          discordUrl: response.data.discordUrl || '',
          youtubeUrl: response.data.youtubeUrl || '',
          telegramUrl: response.data.telegramUrl || '',
        });
        setIsTwoFAEnabled(response.data.twoFactorEnabled);
        setIsEmailVerified(Boolean(response.data.emailVerified));
        setVerificationEmail(response.data.email || '');
      } catch (error: any) {
        toast.error('Không thể tải thông tin hồ sơ');
        console.error('Error fetching profile:', error);
      } finally {
        setLoading(false);
      }
    };

    if (user?.id) {
      fetchProfile();
    }
  }, [user?.id]);

  const handleChange = (e: React.ChangeEvent<HTMLInputElement | HTMLTextAreaElement>) => {
    const { name, value } = e.target;
    setProfile(prev => ({ ...prev, [name]: value }));
    if (errors[name]) setErrors(prev => ({ ...prev, [name]: '' }));
  };

  const requestEmailVerification = async () => {
    setEmailVerificationLoading(true);
    try {
      const response = await api.post('/auth/email-verification/request', { email: verificationEmail });
      if (response.data.alreadyVerified) { setIsEmailVerified(true); return; }
      setEmailChallenge({ id: response.data.challengeId, maskedEmail: response.data.maskedEmail, expiresAt: response.data.expiresAt, resendAvailableAt: response.data.resendAvailableAt });
      toast.success('Mã xác minh đã được gửi tới email của bạn.');
    } catch (error: any) {
      toast.error(error.response?.data?.message || 'Không thể gửi mã xác minh email.');
    } finally { setEmailVerificationLoading(false); }
  };

  const verifyEmailCode = async () => {
    if (!emailChallenge || verificationCode.length !== 6) return;
    setEmailVerificationLoading(true);
    try {
      await api.post('/auth/email-verification/verify', { challengeId: emailChallenge.id, code: verificationCode });
      setIsEmailVerified(true);
      setEmailChallenge(null);
      setVerificationCode('');
      toast.success('Email đã được xác minh thành công.');
    } catch (error: any) {
      toast.error(error.response?.data?.message || 'Mã xác minh không đúng.');
    } finally { setEmailVerificationLoading(false); }
  };

  const resendEmailVerification = async () => {
    if (!emailChallenge) return;
    setEmailVerificationLoading(true);
    try {
      const response = await api.post('/auth/email-verification/resend', { challengeId: emailChallenge.id });
      setEmailChallenge((current) => current ? { ...current, expiresAt: response.data.expiresAt, resendAvailableAt: response.data.resendAvailableAt } : current);
      toast.success('Đã gửi lại mã xác minh.');
    } catch (error: any) {
      toast.error(error.response?.data?.message || 'Chưa thể gửi lại mã.');
    } finally { setEmailVerificationLoading(false); }
  };

  const scrollToSection = (section: 'basic' | 'security' | 'notifications' | 'privacy') => {
    setActiveSection(section);
    const element = document.getElementById(`section-${section}`);
    element?.scrollIntoView({ behavior: 'smooth', block: 'start' });
  };

  const handleDeleteAccount = async () => {
    setShowDeleteModal(false);
    if (!window.confirm('Bạn có chắc chắn muốn xóa tài khoản? Hành động này không thể hoàn tác.')) return;
    setDeleting(true);
    try {
      await api.delete('/auth/profile');
      toast.success('Tài khoản đã được xóa.');
      logout();
      window.location.href = '/vi/auth/login';
    } catch (error: any) {
      toast.error(error.response?.data?.message || 'Xóa tài khoản thất bại.');
    } finally {
      setDeleting(false);
    }
  };

  const validateProfile = () => {
    const newErrors: { [key: string]: string } = {};
    if (!profile.name.trim()) newErrors.name = 'Vui lòng nhập họ và tên';
    setErrors(newErrors);
    return Object.keys(newErrors).length === 0;
  };

  const handleSave = async () => {
    if (!validateProfile()) return;
    setSaving(true);
    try {
      const updateData = {
        name: profile.name,
        phone: profile.phone,
        address: profile.address,
        city: profile.city,
        district: profile.district,
        ward: profile.ward,
        facebookUrl: profile.facebookUrl || undefined,
        discordUrl: profile.discordUrl || undefined,
        youtubeUrl: profile.youtubeUrl || undefined,
        telegramUrl: profile.telegramUrl || undefined,
      };
      await api.put('/auth/profile', updateData);
      toast.success('Cập nhật thông tin thành công!', { position: 'top-center' });
      setTimeout(() => window.history.back(), 1500);
    } catch (error: any) {
      toast.error(error.response?.data?.message || 'Có lỗi xảy ra!');
    } finally {
      setSaving(false);
    }
  };

  // Password change handlers
  const handlePasswordChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    const { name, value } = e.target;
    setPasswords(prev => ({ ...prev, [name]: value }));
    if (passwordErrors[name]) setPasswordErrors(prev => ({ ...prev, [name]: '' }));
  };

  const validatePassword = () => {
    const newErrors: { [key: string]: string } = {};
    if (!passwords.currentPassword) newErrors.currentPassword = 'Vui lòng nhập mật khẩu hiện tại';
    if (!passwords.newPassword) newErrors.newPassword = 'Vui lòng nhập mật khẩu mới';
    if (passwords.newPassword.length < 8) newErrors.newPassword = 'Mật khẩu mới phải có ít nhất 8 ký tự';
    if (passwords.newPassword !== passwords.confirmPassword) newErrors.confirmPassword = 'Mật khẩu xác nhận không khớp';
    setPasswordErrors(newErrors);
    return Object.keys(newErrors).length === 0;
  };

  const handleChangePassword = async () => {
    if (!validatePassword()) return;
    setPasswordLoading(true);
    try {
      await api.post('/auth/change-password', {
        currentPassword: passwords.currentPassword,
        newPassword: passwords.newPassword,
        confirmPassword: passwords.confirmPassword,
      });
      toast.success('Đổi mật khẩu thành công!');
      setShowPasswordModal(false);
      setPasswords({ currentPassword: '', newPassword: '', confirmPassword: '' });
    } catch (error: any) {
      toast.error(error.response?.data?.message || 'Có lỗi xảy ra!');
    } finally {
      setPasswordLoading(false);
    }
  };

  // 2FA handlers
  const handleEnable2FA = async () => {
    try {
      setTwoFALoading(true);
      const response = await api.post('/auth/2fa/enable');
      setTwoFASecret(response.data.secret);
      toast.success('Quét mã QR hoặc nhập khóa thủ công vào ứng dụng xác thực');
    } catch (error: any) {
      toast.error(error.response?.data?.message || 'Có lỗi xảy ra!');
    } finally {
      setTwoFALoading(false);
    }
  };

  const handleVerify2FA = async () => {
    if (!twoFACode || twoFACode.length !== 6) {
      toast.error('Vui lòng nhập mã xác thực 6 chữ số');
      return;
    }
    try {
      setTwoFALoading(true);
      await api.post('/auth/2fa/verify', { code: twoFACode });
      toast.success('Xác thực 2FA đã được bật!');
      setIsTwoFAEnabled(true);
      setShow2faModal(false);
      setTwoFASecret('');
      setTwoFACode('');
    } catch (error: any) {
      toast.error(error.response?.data?.message || 'Mã xác thực không đúng!');
    } finally {
      setTwoFALoading(false);
    }
  };

  const handleDisable2FA = async () => {
    if (!window.confirm('Bạn có chắc chắn muốn tắt xác thực 2FA?')) return;
    try {
      await api.post('/auth/2fa/disable');
      toast.success('Xác thực 2FA đã được tắt');
      setIsTwoFAEnabled(false);
    } catch (error: any) {
      toast.error(error.response?.data?.message || 'Có lỗi xảy ra!');
    }
  };

  return (
    <>
      <Toaster />
      <Navbar />
      <div className="min-h-[calc(100vh-64px)] bg-[#0a0a0a]">
        <div className="max-w-7xl mx-auto px-4 py-6">

          {/* Header with Back Button */}
          <div className="flex items-center gap-4 mb-6">
            <Link href="/vi/profile">
              <button className="flex items-center gap-2 px-4 py-2 bg-[#15161a] hover:bg-white/5 border border-white/5 rounded-lg text-gray-300 hover:text-white transition-colors">
                <ArrowLeft className="w-4 h-4" /> Quay lại
              </button>
            </Link>
            <div>
              <h1 className="text-2xl font-bold text-white">Chỉnh sửa hồ sơ</h1>
              <p className="text-sm text-gray-400">Cập nhật thông tin cá nhân của bạn</p>
            </div>
          </div>

          <div className="grid grid-cols-1 lg:grid-cols-4 gap-6">

            {/* Sidebar Menu */}
            <div className="lg:col-span-1">
              <div className="bg-[#15161a] border border-white/5 rounded-2xl p-4 sticky top-20 space-y-1">
                <p className="text-xs font-bold text-gray-400 uppercase tracking-wider px-3 py-2">CÀI ĐẶT TÀI KHOẢN</p>

                <button
                  onClick={() => scrollToSection('basic')}
                  className={`w-full flex items-center gap-3 px-3 py-3 rounded-lg text-sm font-medium transition-colors ${activeSection === 'basic' ? 'bg-red-600/20 text-red-300 border border-red-600/30' : 'text-gray-400 hover:bg-white/5'}`}
                >
                  <User className="w-4 h-4" />
                  <span>Thông tin cơ bản</span>
                </button>

                <button
                  onClick={() => scrollToSection('security')}
                  className={`w-full flex items-center gap-3 px-3 py-3 rounded-lg text-sm font-medium transition-colors ${activeSection === 'security' ? 'bg-red-600/20 text-red-300 border border-red-600/30' : 'text-gray-400 hover:bg-white/5'}`}
                >
                  <Shield className="w-4 h-4" />
                  <span>Bảo mật</span>
                </button>

                <button
                  onClick={() => scrollToSection('notifications')}
                  className={`w-full flex items-center gap-3 px-3 py-3 rounded-lg text-sm font-medium transition-colors ${activeSection === 'notifications' ? 'bg-red-600/20 text-red-300 border border-red-600/30' : 'text-gray-400 hover:bg-white/5'}`}
                >
                  <Bell className="w-4 h-4" />
                  <span>Thông báo</span>
                </button>

                <button
                  onClick={() => scrollToSection('privacy')}
                  className={`w-full flex items-center gap-3 px-3 py-3 rounded-lg text-sm font-medium transition-colors ${activeSection === 'privacy' ? 'bg-red-600/20 text-red-300 border border-red-600/30' : 'text-gray-400 hover:bg-white/5'}`}
                >
                  <Lock className="w-4 h-4" />
                  <span>Quyền riêng tư</span>
                </button>

                <hr className="my-2 border-white/5" />

                <button
                  onClick={() => setShowDeleteModal(true)}
                  className="w-full flex items-center gap-3 px-3 py-3 text-gray-400 text-sm font-medium hover:bg-white/5 rounded-lg transition-colors"
                >
                  <Trash2 className="w-4 h-4" />
                  <span>Xóa tài khoản</span>
                </button>
              </div>
            </div>

            {/* Main Content */}
            <div className="lg:col-span-3 space-y-6">

              {/* Thông tin cơ bản */}
              <div className="bg-[#15161a] border border-white/5 rounded-2xl p-6">
                <h2 className="text-xl font-bold text-white mb-6">Thông tin cơ bản</h2>

                <div className="space-y-6">
                  {/* Name */}
                  <div className="space-y-2">
                    <label className="text-sm font-medium text-gray-300">Họ và tên <span className="text-red-500">*</span></label>
                    <input
                      type="text"
                      name="name"
                      value={profile.name}
                      onChange={handleChange}
                      maxLength={100}
                      className={`w-full bg-[#0a0b0d] border rounded-xl px-4 py-3 text-white text-sm focus:outline-none transition-colors ${
                        errors.name ? 'border-red-500' : 'border-white/10 focus:border-primary'
                      }`}
                    />
                    {errors.name && (
                      <p className="text-xs text-red-500 flex items-center gap-1">
                        <AlertCircle className="w-3 h-3" /> {errors.name}
                      </p>
                    )}
                    <div className="flex justify-between">
                      <p className="text-xs text-gray-500">Tên đầy đủ của bạn</p>
                      <p className="text-xs text-gray-500">{profile.name.length}/100</p>
                    </div>
                  </div>

                  {/* Email */}
                  <div className="space-y-2">
                    <label className="text-sm font-medium text-gray-300">Email</label>
                    <input
                      type="email"
                      value={profile.email}
                      disabled
                      className="w-full bg-[#0a0b0d] border border-white/5 rounded-xl px-4 py-3 text-gray-500 text-sm cursor-not-allowed opacity-50"
                    />
                    <p className="text-xs text-gray-500">Email không thể thay đổi. Liên hệ support nếu cần hỗ trợ.</p>
                  </div>

                  {/* Phone */}
                  <div className="space-y-2">
                    <label className="text-sm font-medium text-gray-300">Số điện thoại</label>
                    <input
                      type="tel"
                      name="phone"
                      value={profile.phone}
                      onChange={handleChange}
                      placeholder="0123456789"
                      className="w-full bg-[#0a0b0d] border border-white/10 rounded-xl px-4 py-3 text-white text-sm focus:outline-none focus:border-primary transition-colors"
                    />
                    <p className="text-xs text-gray-500">Số điện thoại công khai để khách hàng liên hệ</p>
                  </div>

                  {/* Address */}
                  <div className="space-y-2">
                    <label className="text-sm font-medium text-gray-300">Địa chỉ</label>
                    <input
                      type="text"
                      name="address"
                      value={profile.address}
                      onChange={handleChange}
                      placeholder="Số nhà, đường phố"
                      className="w-full bg-[#0a0b0d] border border-white/10 rounded-xl px-4 py-3 text-white text-sm focus:outline-none focus:border-primary transition-colors"
                    />
                    <p className="text-xs text-gray-500">Địa chỉ cụ thể của bạn</p>
                  </div>

                  {/* City, District, Ward */}
                  <div className="grid grid-cols-1 md:grid-cols-3 gap-4">
                    <div className="space-y-2">
                      <label className="text-sm font-medium text-gray-300">Tỉnh/Thành phố</label>
                      <input
                        type="text"
                        name="city"
                        value={profile.city}
                        onChange={handleChange}
                        placeholder="Hà Nội"
                        className="w-full bg-[#0a0b0d] border border-white/10 rounded-xl px-4 py-3 text-white text-sm focus:outline-none focus:border-primary transition-colors"
                      />
                    </div>
                    <div className="space-y-2">
                      <label className="text-sm font-medium text-gray-300">Quận/Huyện</label>
                      <input
                        type="text"
                        name="district"
                        value={profile.district}
                        onChange={handleChange}
                        placeholder="Hoàn Kiếm"
                        className="w-full bg-[#0a0b0d] border border-white/10 rounded-xl px-4 py-3 text-white text-sm focus:outline-none focus:border-primary transition-colors"
                      />
                    </div>
                    <div className="space-y-2">
                      <label className="text-sm font-medium text-gray-300">Phường/Xã</label>
                      <input
                        type="text"
                        name="ward"
                        value={profile.ward}
                        onChange={handleChange}
                        placeholder="Hàng Đậu"
                        className="w-full bg-[#0a0b0d] border border-white/10 rounded-xl px-4 py-3 text-white text-sm focus:outline-none focus:border-primary transition-colors"
                      />
                    </div>
                  </div>

                  <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                    <div className="space-y-2">
                      <label className="text-sm font-medium text-gray-300">Facebook URL</label>
                      <input
                        type="url"
                        name="facebookUrl"
                        value={profile.facebookUrl}
                        onChange={handleChange}
                        placeholder="https://www.facebook.com/yourpage"
                        className="w-full bg-[#0a0b0d] border border-white/10 rounded-xl px-4 py-3 text-white text-sm focus:outline-none focus:border-primary transition-colors"
                      />
                      <p className="text-xs text-gray-500">Link fanpage hoặc profile Facebook.</p>
                    </div>
                    <div className="space-y-2">
                      <label className="text-sm font-medium text-gray-300">Discord URL</label>
                      <input
                        type="url"
                        name="discordUrl"
                        value={profile.discordUrl}
                        onChange={handleChange}
                        placeholder="https://discord.gg/yourserver"
                        className="w-full bg-[#0a0b0d] border border-white/10 rounded-xl px-4 py-3 text-white text-sm focus:outline-none focus:border-primary transition-colors"
                      />
                      <p className="text-xs text-gray-500">Link invite Discord của bạn.</p>
                    </div>
                  </div>

                  <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                    <div className="space-y-2">
                      <label className="text-sm font-medium text-gray-300">YouTube URL</label>
                      <input
                        type="url"
                        name="youtubeUrl"
                        value={profile.youtubeUrl}
                        onChange={handleChange}
                        placeholder="https://www.youtube.com/channel/yourchannel"
                        className="w-full bg-[#0a0b0d] border border-white/10 rounded-xl px-4 py-3 text-white text-sm focus:outline-none focus:border-primary transition-colors"
                      />
                      <p className="text-xs text-gray-500">Link kênh YouTube.</p>
                    </div>
                    <div className="space-y-2">
                      <label className="text-sm font-medium text-gray-300">Telegram URL</label>
                      <input
                        type="url"
                        name="telegramUrl"
                        value={profile.telegramUrl}
                        onChange={handleChange}
                        placeholder="https://t.me/yourchannel"
                        className="w-full bg-[#0a0b0d] border border-white/10 rounded-xl px-4 py-3 text-white text-sm focus:outline-none focus:border-primary transition-colors"
                      />
                      <p className="text-xs text-gray-500">Link kênh Telegram của bạn.</p>
                    </div>
                  </div>
                </div>

                {/* Action Buttons */}
                <div className="flex gap-3 mt-8 pt-6 border-t border-white/5">
                  <button
                    onClick={handleSave}
                    disabled={saving}
                    className="flex-1 flex items-center justify-center gap-2 py-3 bg-red-600 hover:bg-red-700 disabled:opacity-50 text-white font-semibold rounded-xl transition-colors"
                  >
                    {saving && <Loader2 className="w-4 h-4 animate-spin" />}
                    {saving ? 'Đang lưu...' : 'Lưu thay đổi'}
                  </button>
                  <Link href="/vi/profile" className="flex-1">
                    <button className="w-full py-3 bg-white/5 hover:bg-white/10 text-white font-semibold rounded-xl transition-colors">
                      Hủy bỏ
                    </button>
                  </Link>
                </div>
              </div>

              {/* Bảo mật tài khoản */}
              <div id="section-security" className="bg-[#15161a] border border-white/5 rounded-2xl p-6">
                <h2 className="text-xl font-bold text-white mb-6 flex items-center gap-2">
                  <Shield className="w-5 h-5 text-red-500" /> Bảo mật tài khoản
                </h2>

                <div className="space-y-3">
                  <button
                    onClick={() => setShowPasswordModal(true)}
                    className="w-full flex items-center justify-between p-4 bg-[#0a0b0d] hover:bg-white/5 border border-white/10 rounded-xl transition-colors">
                    <div className="text-left flex items-center gap-3">
                      <Lock className="w-5 h-5 text-gray-400" />
                      <div>
                        <p className="font-medium text-white">Đổi mật khẩu</p>
                        <p className="text-xs text-gray-500">Cập nhật mật khẩu của bạn để bảo vệ tài khoản</p>
                      </div>
                    </div>
                    <ChevronRight className="w-4 h-4 text-gray-600" />
                  </button>

                  <button
                    onClick={() => !isTwoFAEnabled ? setShow2faModal(true) : handleDisable2FA()}
                    className="w-full flex items-center justify-between p-4 bg-[#0a0b0d] hover:bg-white/5 border border-white/10 rounded-xl transition-colors">
                    <div className="text-left flex items-center gap-3">
                      <Zap className="w-5 h-5 text-gray-400" />
                      <div>
                        <p className="font-medium text-white">Xác thực 2 yếu tố (2FA)</p>
                        <p className="text-xs text-gray-500">{isTwoFAEnabled ? '✓ Đã bật' : 'Chưa bật'} · Bảo vệ tài khoản bằng 2FA</p>
                      </div>
                    </div>
                    <ChevronRight className="w-4 h-4 text-gray-600" />
                  </button>

                  <div className={`p-4 rounded-xl border ${isEmailVerified ? 'bg-green-500/10 border-green-500/20' : 'bg-amber-500/10 border-amber-500/20'}`}>
                    <p className={`text-sm font-medium ${isEmailVerified ? 'text-green-400' : 'text-amber-300'}`}>{isEmailVerified ? '✓ Email đã xác minh' : '⚠ Email chưa xác minh'}</p>
                    <p className={`text-xs mt-1 ${isEmailVerified ? 'text-green-300' : 'text-amber-200'}`}>{isEmailVerified ? 'Email của bạn đã được xác minh' : 'Vui lòng xác minh email để bảo vệ tài khoản'}</p>
                    {!isEmailVerified && <div className="mt-3 space-y-2">
                      <input type="email" value={verificationEmail} onChange={(event) => setVerificationEmail(event.target.value)} placeholder="Email cần xác minh" className="w-full rounded-lg border border-white/10 bg-black/30 px-3 py-2 text-sm text-white" />
                       <button type="button" onClick={() => void requestEmailVerification()} disabled={emailVerificationLoading || !verificationEmail} className="rounded-lg bg-amber-500 px-3 py-2 text-sm font-bold text-black disabled:opacity-50">{emailVerificationLoading ? 'Đang gửi...' : 'Gửi mã xác minh'}</button>
                    </div>}
                    {emailChallenge && !isEmailVerified && <div className="mt-3 space-y-2 rounded-lg border border-white/10 bg-black/20 p-3"><p className="text-xs text-amber-100">Mã đã gửi tới {emailChallenge.maskedEmail}. Có hiệu lực đến {new Date(emailChallenge.expiresAt).toLocaleTimeString('vi-VN')}.</p><input inputMode="numeric" maxLength={6} value={verificationCode} onChange={(event) => setVerificationCode(event.target.value.replace(/\D/g, '').slice(0, 6))} placeholder="Nhập mã 6 số" className="w-full rounded-lg border border-white/10 bg-black/30 px-3 py-2 text-sm tracking-[0.3em] text-white" /><div className="flex gap-2"><button type="button" onClick={() => void verifyEmailCode()} disabled={emailVerificationLoading || verificationCode.length !== 6} className="rounded-lg bg-green-500 px-3 py-2 text-sm font-bold text-black disabled:opacity-50">Xác minh</button><button type="button" onClick={() => void resendEmailVerification()} disabled={emailVerificationLoading} className="rounded-lg border border-white/10 px-3 py-2 text-sm font-bold text-white disabled:opacity-50">Gửi lại mã</button></div></div>}
                  </div>
                </div>
              </div>

              {/* Notifications */}
              <div id="section-notifications" className="bg-[#15161a] border border-white/5 rounded-2xl p-6">
                <h2 className="text-xl font-bold text-white mb-6 flex items-center gap-2">
                  <Bell className="w-5 h-5 text-yellow-500" /> Thông báo
                </h2>
                <div className="space-y-4">
                  <div className="p-4 bg-[#0a0b0d] border border-white/10 rounded-xl">
                    <div className="flex items-center justify-between gap-4">
                      <div>
                        <p className="font-medium text-white">Email thông báo</p>
                        <p className="text-xs text-gray-500">Nhận email khi có cập nhật đơn hàng và tin tức.</p>
                      </div>
                      <button
                        onClick={() => setEmailNotifications(prev => !prev)}
                        className={`px-4 py-2 rounded-full text-sm font-medium transition ${emailNotifications ? 'bg-red-600 text-white' : 'bg-white/5 text-gray-300 hover:bg-white/10'}`}
                      >
                        {emailNotifications ? 'Bật' : 'Tắt'}
                      </button>
                    </div>
                  </div>
                  <div className="p-4 bg-[#0a0b0d] border border-white/10 rounded-xl">
                    <div className="flex items-center justify-between gap-4">
                      <div>
                        <p className="font-medium text-white">Thông báo đẩy</p>
                        <p className="text-xs text-gray-500">Nhận thông báo ngay trên thiết bị của bạn.</p>
                      </div>
                      <button
                        onClick={() => setPushNotifications(prev => !prev)}
                        className={`px-4 py-2 rounded-full text-sm font-medium transition ${pushNotifications ? 'bg-red-600 text-white' : 'bg-white/5 text-gray-300 hover:bg-white/10'}`}
                      >
                        {pushNotifications ? 'Bật' : 'Tắt'}
                      </button>
                    </div>
                  </div>
                </div>
              </div>

              {/* Privacy */}
              <div id="section-privacy" className="bg-[#15161a] border border-white/5 rounded-2xl p-6">
                <h2 className="text-xl font-bold text-white mb-6 flex items-center gap-2">
                  <Lock className="w-5 h-5 text-blue-500" /> Quyền riêng tư
                </h2>
                <div className="space-y-4">
                  <div className="p-4 bg-[#0a0b0d] border border-white/10 rounded-xl">
                    <div className="flex items-center justify-between gap-4">
                      <div>
                        <p className="font-medium text-white">Hồ sơ công khai</p>
                        <p className="text-xs text-gray-500">Cho phép khách truy cập xem trang cá nhân của bạn.</p>
                      </div>
                      <button
                        onClick={() => setPublicProfile(prev => !prev)}
                        className={`px-4 py-2 rounded-full text-sm font-medium transition ${publicProfile ? 'bg-red-600 text-white' : 'bg-white/5 text-gray-300 hover:bg-white/10'}`}
                      >
                        {publicProfile ? 'Bật' : 'Tắt'}
                      </button>
                    </div>
                  </div>
                  <div className="p-4 bg-[#0a0b0d] border border-white/10 rounded-xl">
                    <p className="text-sm text-gray-400">Các cài đặt quyền riêng tư hiện chỉ lưu tạm thời trong phiên bản này.</p>
                  </div>
                </div>
              </div>

              {/* Devices & Sessions */}
              <div className="bg-[#15161a] border border-white/5 rounded-2xl p-6">
                <h2 className="text-xl font-bold text-white mb-6">Thiết bị & Phiên đăng nhập</h2>

                <div className="space-y-3">
                  <div className="p-4 bg-[#0a0b0d] border border-white/10 rounded-xl">
                    <div className="flex items-center justify-between">
                      <div>
                        <p className="font-medium text-white">Chrome · Windows</p>
                        <p className="text-xs text-gray-500 mt-1">IP: 192.168.1.1 · Vừa hoạt động lúc</p>
                      </div>
                      <span className="text-xs bg-green-500/10 text-green-400 px-3 py-1 rounded-full">Hiện tại</span>
                    </div>
                  </div>
                </div>
              </div>

            </div>

          </div>

        </div>
      </div>

      {/* Password Change Modal */}
      {showPasswordModal && (
        <div className="fixed inset-0 bg-black/50 backdrop-blur-sm flex items-center justify-center z-50 p-4">
          <div className="bg-[#15161a] border border-white/10 rounded-2xl max-w-md w-full p-6 space-y-6">
            <div className="flex items-center justify-between">
              <h3 className="text-xl font-bold text-white">Đổi mật khẩu</h3>
              <button onClick={() => setShowPasswordModal(false)} className="text-gray-400 hover:text-white">
                <X className="w-5 h-5" />
              </button>
            </div>

            <div className="space-y-4">
              {/* Current Password */}
              <div className="space-y-2">
                <label className="text-sm font-medium text-gray-300">Mật khẩu hiện tại</label>
                <input
                  type="password"
                  name="currentPassword"
                  value={passwords.currentPassword}
                  onChange={handlePasswordChange}
                  className={`w-full bg-[#0a0b0d] border rounded-xl px-4 py-3 text-white text-sm focus:outline-none transition-colors ${
                    passwordErrors.currentPassword ? 'border-red-500' : 'border-white/10 focus:border-primary'
                  }`}
                />
                {passwordErrors.currentPassword && (
                  <p className="text-xs text-red-500">{passwordErrors.currentPassword}</p>
                )}
              </div>

              {/* New Password */}
              <div className="space-y-2">
                <label className="text-sm font-medium text-gray-300">Mật khẩu mới</label>
                <input
                  type="password"
                  name="newPassword"
                  value={passwords.newPassword}
                  onChange={handlePasswordChange}
                  className={`w-full bg-[#0a0b0d] border rounded-xl px-4 py-3 text-white text-sm focus:outline-none transition-colors ${
                    passwordErrors.newPassword ? 'border-red-500' : 'border-white/10 focus:border-primary'
                  }`}
                />
                {passwordErrors.newPassword && (
                  <p className="text-xs text-red-500">{passwordErrors.newPassword}</p>
                )}
              </div>

              {/* Confirm Password */}
              <div className="space-y-2">
                <label className="text-sm font-medium text-gray-300">Xác nhận mật khẩu</label>
                <input
                  type="password"
                  name="confirmPassword"
                  value={passwords.confirmPassword}
                  onChange={handlePasswordChange}
                  className={`w-full bg-[#0a0b0d] border rounded-xl px-4 py-3 text-white text-sm focus:outline-none transition-colors ${
                    passwordErrors.confirmPassword ? 'border-red-500' : 'border-white/10 focus:border-primary'
                  }`}
                />
                {passwordErrors.confirmPassword && (
                  <p className="text-xs text-red-500">{passwordErrors.confirmPassword}</p>
                )}
              </div>
            </div>

            <div className="flex gap-3 pt-4 border-t border-white/5">
              <button
                onClick={() => setShowPasswordModal(false)}
                className="flex-1 py-2 bg-white/5 hover:bg-white/10 text-white font-medium rounded-xl transition-colors"
              >
                Hủy
              </button>
              <button
                onClick={handleChangePassword}
                disabled={passwordLoading}
                className="flex-1 py-2 bg-red-600 hover:bg-red-700 disabled:opacity-50 text-white font-medium rounded-xl transition-colors flex items-center justify-center gap-2"
              >
                {passwordLoading && <Loader2 className="w-4 h-4 animate-spin" />}
                Xác nhận
              </button>
            </div>
          </div>
        </div>
      )}

      {/* 2FA Modal */}
      {show2faModal && (
        <div className="fixed inset-0 bg-black/50 backdrop-blur-sm flex items-center justify-center z-50 p-4">
          <div className="bg-[#15161a] border border-white/10 rounded-2xl max-w-md w-full p-6 space-y-6">
            <div className="flex items-center justify-between">
              <h3 className="text-xl font-bold text-white">Kích hoạt xác thực 2FA</h3>
              <button onClick={() => { setShow2faModal(false); setTwoFASecret(''); setTwoFACode(''); }} className="text-gray-400 hover:text-white">
                <X className="w-5 h-5" />
              </button>
            </div>

            {!twoFASecret ? (
              <div className="space-y-4">
                <p className="text-sm text-gray-400">
                  Xác thực 2FA sẽ bảo vệ tài khoản của bạn bằng cách yêu cầu mã xác thực từ ứng dụng authenticator.
                </p>
                <button
                  onClick={handleEnable2FA}
                  disabled={twoFALoading}
                  className="w-full py-3 bg-red-600 hover:bg-red-700 disabled:opacity-50 text-white font-semibold rounded-xl transition-colors flex items-center justify-center gap-2"
                >
                  {twoFALoading && <Loader2 className="w-4 h-4 animate-spin" />}
                  Tiếp tục
                </button>
              </div>
            ) : (
              <div className="space-y-4">
                <div className="bg-[#0a0b0d] border border-white/10 rounded-xl p-4 space-y-3">
                  <p className="text-sm text-gray-400">Khóa bí mật của bạn:</p>
                  <div className="bg-[#15161a] rounded-lg p-3 font-mono text-sm text-white break-all">{twoFASecret}</div>
                  <p className="text-xs text-gray-500">
                    Sao chép khóa này nếu quét mã QR không hoạt động. Nhập vào ứng dụng xác thực như Google Authenticator, Microsoft Authenticator, v.v.
                  </p>
                </div>

                <div className="space-y-2">
                  <label className="text-sm font-medium text-gray-300">Nhập mã 6 chữ số từ ứng dụng xác thực</label>
                  <input
                    type="text"
                    value={twoFACode}
                    onChange={(e) => setTwoFACode(e.target.value.slice(0, 6))}
                    maxLength={6}
                    placeholder="000000"
                    className="w-full bg-[#0a0b0d] border border-white/10 rounded-xl px-4 py-3 text-white text-center text-lg font-mono focus:outline-none focus:border-primary transition-colors"
                  />
                </div>

                <button
                  onClick={handleVerify2FA}
                  disabled={twoFALoading || twoFACode.length !== 6}
                  className="w-full py-3 bg-red-600 hover:bg-red-700 disabled:opacity-50 text-white font-semibold rounded-xl transition-colors flex items-center justify-center gap-2"
                >
                  {twoFALoading && <Loader2 className="w-4 h-4 animate-spin" />}
                  Xác minh và bật
                </button>
              </div>
            )}

            {!twoFASecret && (
              <button
                onClick={() => { setShow2faModal(false); setTwoFASecret(''); setTwoFACode(''); }}
                className="w-full py-2 bg-white/5 hover:bg-white/10 text-white font-medium rounded-xl transition-colors"
              >
                Hủy
              </button>
            )}
          </div>
        </div>
      )}

      {/* Delete account modal */}
      {showDeleteModal && (
        <div className="fixed inset-0 bg-black/50 backdrop-blur-sm flex items-center justify-center z-50 p-4">
          <div className="bg-[#15161a] border border-white/10 rounded-2xl max-w-md w-full p-6 space-y-6">
            <div className="flex items-center justify-between">
              <div>
                <h3 className="text-xl font-bold text-white">Xóa tài khoản</h3>
                <p className="text-sm text-gray-400">Hành động này sẽ vô hiệu hóa tài khoản của bạn và không thể hoàn tác.</p>
              </div>
              <button onClick={() => setShowDeleteModal(false)} className="text-gray-400 hover:text-white">
                <X className="w-5 h-5" />
              </button>
            </div>
            <div className="space-y-4">
              <p className="text-sm text-red-300">Bạn vẫn có thể khôi phục nếu liên hệ với Bộ phận hỗ trợ trong vòng 24 giờ.</p>
              <div className="rounded-xl bg-[#0a0b0d] border border-white/10 p-4 text-sm text-gray-300">
                <p className="font-medium text-white">Lưu ý:</p>
                <ul className="list-disc list-inside space-y-1 mt-2 text-gray-400">
                  <li>Tài khoản sẽ bị gán trạng thái DELETED.</li>
                  <li>Toàn bộ dữ liệu đặt hàng và ví vẫn được giữ lại.</li>
                  <li>Bạn sẽ bị đăng xuất ngay lập tức.</li>
                </ul>
              </div>
            </div>
            <div className="flex gap-3 pt-4 border-t border-white/5">
              <button
                onClick={() => setShowDeleteModal(false)}
                className="flex-1 py-2 bg-white/5 hover:bg-white/10 text-white font-medium rounded-xl transition-colors"
              >
                Hủy
              </button>
              <button
                onClick={handleDeleteAccount}
                disabled={deleting}
                className="flex-1 py-2 bg-red-600 hover:bg-red-700 disabled:opacity-50 text-white font-medium rounded-xl transition-colors"
              >
                {deleting ? 'Đang xóa...' : 'Xóa tài khoản'}
              </button>
            </div>
          </div>
        </div>
      )}
    </>
  );
}
