'use client';

import { useState } from 'react';
import { useRouter } from 'next/navigation';
import Link from 'next/link';
import { 
  Mail,
  Loader2,
  CheckCircle,
  AlertCircle,
  Shield
} from 'lucide-react';
import { useLanguage } from '@/i18n/LanguageContext';

export default function EmailPage() {
  const router = useRouter();
  const { t } = useLanguage();
  const [isLoading, setIsLoading] = useState(false);
  const [success, setSuccess] = useState('');
  const [error, setError] = useState('');
  const [step, setStep] = useState<'password' | 'email'>('password');
  const [password, setPassword] = useState('');
  const [newEmail, setNewEmail] = useState('');

  const handlePasswordCheck = async (e: React.FormEvent) => {
    e.preventDefault();
    setIsLoading(true);
    setError('');

    try {
      const response = await fetch('/api/user/verify-password', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ password }),
      });

      const data = await response.json();

      if (response.ok) {
        setStep('email');
      } else {
        setError(data.error || t.user.settings.passwordVerifyFailed);
      }
    } catch (err) {
      setError(t.user.settings.networkError);
    } finally {
      setIsLoading(false);
    }
  };

  const handleEmailChange = async (e: React.FormEvent) => {
    e.preventDefault();
    setIsLoading(true);
    setError('');

    try {
      const response = await fetch('/api/user/email', {
        method: 'PUT',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          password,
          newEmail,
        }),
      });

      const data = await response.json();

      if (response.ok) {
        setSuccess(t.user.settings.emailSuccess);
        setStep('password');
        setPassword('');
        setNewEmail('');
      } else {
        setError(data.error || t.user.settings.emailFailed);
      }
    } catch (err) {
      setError(t.user.settings.networkError);
    } finally {
      setIsLoading(false);
    }
  };

  return (
    <div className="max-w-3xl mx-auto">
      {/* 页面标题 */}
      <div className="mb-6">
        <h1 className="text-2xl font-bold text-gray-900">{t.user.settings.changeEmailTitle}</h1>
        <p className="text-gray-500 mt-1">{t.user.settings.changeEmailDesc}</p>
      </div>

      {/* 设置导航 */}
      <div className="flex gap-2 mb-6 overflow-x-auto pb-2">
        <Link
          href="/user/settings"
          className="flex-shrink-0 px-4 py-2 bg-white text-gray-600 text-sm font-medium rounded-lg border border-gray-200 hover:bg-gray-50"
        >
          {t.user.editProfile}
        </Link>
        <Link
          href="/user/settings/password"
          className="flex-shrink-0 px-4 py-2 bg-white text-gray-600 text-sm font-medium rounded-lg border border-gray-200 hover:bg-gray-50"
        >
          {t.user.changePassword}
        </Link>
        <Link
          href="/user/settings/email"
          className="flex-shrink-0 px-4 py-2 bg-blue-600 text-white text-sm font-medium rounded-lg"
        >
          {t.user.changeEmail}
        </Link>
      </div>

      {/* 表单 */}
      <div className="bg-white rounded-2xl border border-gray-200 overflow-hidden">
        {/* 步骤指示器 */}
        <div className="flex items-center justify-center gap-4 px-6 py-4 bg-gray-50 border-b border-gray-100">
          <div className={`flex items-center gap-2 ${step === 'password' ? 'text-blue-600' : 'text-green-600'}`}>
            <div className={`w-8 h-8 rounded-full flex items-center justify-center text-sm font-medium ${
              step === 'password' ? 'bg-blue-100 text-blue-600' : 'bg-green-100 text-green-600'
            }`}>
              {step === 'email' ? <CheckCircle className="w-5 h-5" /> : '1'}
            </div>
            <span className="text-sm font-medium">{t.user.settings.step1}</span>
          </div>
          <div className="w-8 border-t border-gray-300"></div>
          <div className={`flex items-center gap-2 ${step === 'email' ? 'text-blue-600' : 'text-gray-400'}`}>
            <div className={`w-8 h-8 rounded-full flex items-center justify-center text-sm font-medium ${
              step === 'email' ? 'bg-blue-100 text-blue-600' : 'bg-gray-100 text-gray-400'
            }`}>
              2
            </div>
            <span className="text-sm font-medium">{t.user.settings.step2}</span>
          </div>
        </div>

        {/* 成功消息 */}
        {success && (
          <div className="mx-6 mt-6 flex items-center gap-2 p-4 bg-green-50 text-green-700 rounded-lg">
            <CheckCircle className="w-5 h-5" />
            <span>{success}</span>
          </div>
        )}

        {/* 错误消息 */}
        {error && (
          <div className="mx-6 mt-6 flex items-center gap-2 p-4 bg-red-50 text-red-700 rounded-lg">
            <AlertCircle className="w-5 h-5" />
            <span>{error}</span>
          </div>
        )}

        {/* 步骤1：验证密码 */}
        {step === 'password' && (
          <form onSubmit={handlePasswordCheck} className="p-6 space-y-6">
            <div className="text-center mb-6">
              <div className="w-16 h-16 bg-blue-50 rounded-full flex items-center justify-center mx-auto mb-4">
                <Shield className="w-8 h-8 text-blue-600" />
              </div>
              <h3 className="text-lg font-medium text-gray-900">{t.user.settings.securityVerify}</h3>
              <p className="text-gray-500 mt-1">{t.user.settings.verifyPasswordDesc}</p>
            </div>

            <div>
              <label className="flex items-center gap-2 text-sm font-medium text-gray-700 mb-2">
                <Shield className="w-4 h-4 text-gray-400" />
                {t.user.settings.loginPassword} <span className="text-red-500">*</span>
              </label>
              <input
                type="password"
                value={password}
                onChange={(e) => setPassword(e.target.value)}
                required
                className="w-full px-4 py-3 border border-gray-200 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-blue-500 outline-none transition-colors"
                placeholder={t.user.settings.passwordPlaceholder}
              />
            </div>

            <div className="pt-4">
              <button
                type="submit"
                disabled={isLoading}
                className="w-full sm:w-auto flex items-center justify-center gap-2 px-6 py-3 bg-blue-600 text-white font-medium rounded-lg hover:bg-blue-700 disabled:opacity-50 disabled:cursor-not-allowed transition-colors"
              >
                {isLoading ? (
                  <Loader2 className="w-5 h-5 animate-spin" />
                ) : (
                  <CheckCircle className="w-5 h-5" />
                )}
                {isLoading ? t.user.settings.verifying : t.user.settings.verify}
              </button>
            </div>
          </form>
        )}

        {/* 步骤2：设置新邮箱 */}
        {step === 'email' && (
          <form onSubmit={handleEmailChange} className="p-6 space-y-6">
            <div className="text-center mb-6">
              <div className="w-16 h-16 bg-blue-50 rounded-full flex items-center justify-center mx-auto mb-4">
                <Mail className="w-8 h-8 text-blue-600" />
              </div>
              <h3 className="text-lg font-medium text-gray-900">{t.user.settings.setNewEmail}</h3>
            </div>

            <div>
              <label className="flex items-center gap-2 text-sm font-medium text-gray-700 mb-2">
                <Mail className="w-4 h-4 text-gray-400" />
                {t.user.settings.newEmail} <span className="text-red-500">*</span>
              </label>
              <input
                type="email"
                value={newEmail}
                onChange={(e) => setNewEmail(e.target.value)}
                required
                className="w-full px-4 py-3 border border-gray-200 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-blue-500 outline-none transition-colors"
                placeholder={t.user.settings.newEmailPlaceholder}
              />
            </div>

            <div className="pt-4">
              <button
                type="submit"
                disabled={isLoading}
                className="w-full sm:w-auto flex items-center justify-center gap-2 px-6 py-3 bg-blue-600 text-white font-medium rounded-lg hover:bg-blue-700 disabled:opacity-50 disabled:cursor-not-allowed transition-colors"
              >
                {isLoading ? (
                  <Loader2 className="w-5 h-5 animate-spin" />
                ) : (
                  <CheckCircle className="w-5 h-5" />
                )}
                {isLoading ? t.user.settings.saving : t.user.settings.save}
              </button>
            </div>
          </form>
        )}
      </div>
    </div>
  );
}
