'use client';

import { useState, useEffect } from 'react';
import { useRouter } from 'next/navigation';
import Link from 'next/link';
import { 
  User,
  Phone,
  Building,
  Mail,
  Save,
  Loader2,
  CheckCircle,
  AlertCircle
} from 'lucide-react';
import { useUser } from '@/contexts/user-context';
import { useLanguage } from '@/i18n/LanguageContext';

export default function SettingsPage() {
  const router = useRouter();
  const { customer, setCustomer, isLoading: userLoading } = useUser();
  const { t, locale } = useLanguage();
  const [isLoading, setIsLoading] = useState(false);
  const [success, setSuccess] = useState('');
  const [error, setError] = useState('');

  const [formData, setFormData] = useState({
    name: '',
    phone: '',
    company: '',
  });

  useEffect(() => {
    if (customer) {
      setFormData({
        name: customer.name,
        phone: customer.phone,
        company: customer.company || '',
      });
    }
  }, [customer]);

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

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

      const data = await response.json();

      if (response.ok) {
        setSuccess(t.user.settings.updateSuccess);
        setCustomer(data.customer);
      } else {
        setError(data.error || t.user.settings.updateFailed);
      }
    } catch (err) {
      setError(t.user.settings.networkError);
    } finally {
      setIsLoading(false);
    }
  };

  if (userLoading) {
    return (
      <div className="flex items-center justify-center py-20">
        <Loader2 className="w-8 h-8 text-blue-600 animate-spin" />
      </div>
    );
  }

  return (
    <div className="max-w-3xl mx-auto">
      {/* 页面标题 */}
      <div className="mb-6">
        <h1 className="text-2xl font-bold text-gray-900">{t.user.settings.editProfileTitle}</h1>
        <p className="text-gray-500 mt-1">{t.user.settings.editProfileDesc}</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-blue-600 text-white text-sm font-medium rounded-lg"
        >
          {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-white text-gray-600 text-sm font-medium rounded-lg border border-gray-200 hover:bg-gray-50"
        >
          {t.user.changeEmail}
        </Link>
      </div>

      {/* 表单 */}
      <div className="bg-white rounded-2xl border border-gray-200 overflow-hidden">
        <form onSubmit={handleSubmit} className="p-6 space-y-6">
          {/* 成功消息 */}
          {success && (
            <div className="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="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>
          )}

          {/* 姓名 */}
          <div>
            <label className="flex items-center gap-2 text-sm font-medium text-gray-700 mb-2">
              <User className="w-4 h-4 text-gray-400" />
              {t.user.settings.name} <span className="text-red-500">*</span>
            </label>
            <input
              type="text"
              value={formData.name}
              onChange={(e) => setFormData({ ...formData, name: 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.namePlaceholder}
            />
          </div>

          {/* 手机号 */}
          <div>
            <label className="flex items-center gap-2 text-sm font-medium text-gray-700 mb-2">
              <Phone className="w-4 h-4 text-gray-400" />
              {t.user.settings.phone} <span className="text-red-500">*</span>
            </label>
            <input
              type="tel"
              value={formData.phone}
              onChange={(e) => setFormData({ ...formData, phone: e.target.value })}
              required
              pattern="[0-9]{11}"
              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.phonePlaceholder}
            />
          </div>

          {/* 公司名称 */}
          <div>
            <label className="flex items-center gap-2 text-sm font-medium text-gray-700 mb-2">
              <Building className="w-4 h-4 text-gray-400" />
              {t.user.settings.company}
            </label>
            <input
              type="text"
              value={formData.company}
              onChange={(e) => setFormData({ ...formData, company: e.target.value })}
              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.companyPlaceholder}
            />
          </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.currentEmail}
            </label>
            <div className="px-4 py-3 bg-gray-50 border border-gray-200 rounded-lg text-gray-500">
              {customer?.email || t.user.settings.noEmail}
            </div>
            <p className="mt-2 text-sm text-gray-400">
              {t.user.settings.goToChangeEmailDesc} <Link href="/user/settings/email" className="text-blue-600 hover:underline">{t.user.settings.goToChangeEmail}</Link> {t.user.settings.page}
            </p>
          </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" />
              ) : (
                <Save className="w-5 h-5" />
              )}
              {isLoading ? t.user.settings.saving : t.user.settings.save}
            </button>
          </div>
        </form>
      </div>
    </div>
  );
}
