import { useState, useEffect } from 'react';
import { useNavigate } from 'react-router-dom';
import { ArrowLeft, User, Phone, Mail, Save, Check } from 'lucide-react';
import { useChatStore } from '@/features/chat/presentation/stores/chatStore';

interface UserProfile {
  id: string;
  type: 'ANONYMOUS' | 'REGISTERED';
  phone?: string;
  nickname?: string;
  avatar?: string;
  sourceChannel?: string;
  createdAt: string;
}

export default function ProfilePage() {
  const navigate = useNavigate();
  const { userId } = useChatStore();
  const [profile, setProfile] = useState<UserProfile | null>(null);
  const [loading, setLoading] = useState(true);
  const [saving, setSaving] = useState(false);
  const [nickname, setNickname] = useState('');
  const [saved, setSaved] = useState(false);

  useEffect(() => {
    if (userId) {
      loadProfile();
    }
  }, [userId]);

  const loadProfile = async () => {
    try {
      const response = await fetch(`/api/v1/users/${userId}`, {
        headers: {
          'x-user-id': userId!,
        },
      });
      const data = await response.json();
      if (data.success && data.data) {
        setProfile(data.data);
        setNickname(data.data.nickname || '');
      }
    } catch (error) {
      console.error('Failed to load profile:', error);
    } finally {
      setLoading(false);
    }
  };

  const handleSave = async () => {
    if (!userId || !nickname.trim()) return;

    setSaving(true);
    try {
      const response = await fetch(`/api/v1/users/${userId}`, {
        method: 'PUT',
        headers: {
          'Content-Type': 'application/json',
          'x-user-id': userId,
        },
        body: JSON.stringify({ nickname: nickname.trim() }),
      });
      const data = await response.json();
      if (data.success) {
        setProfile(data.data);
        setSaved(true);
        setTimeout(() => setSaved(false), 2000);
      }
    } catch (error) {
      console.error('Failed to save profile:', error);
    } finally {
      setSaving(false);
    }
  };

  const formatDate = (dateStr: string) => {
    return new Date(dateStr).toLocaleDateString('zh-CN', {
      year: 'numeric',
      month: 'long',
      day: 'numeric',
    });
  };

  if (loading) {
    return (
      <div className="min-h-screen flex items-center justify-center">
        <div className="w-8 h-8 border-4 border-primary-200 border-t-primary-600 rounded-full animate-spin" />
      </div>
    );
  }

  return (
    <div className="min-h-screen bg-gradient-to-br from-blue-50 to-white">
      {/* Header */}
      <header className="sticky top-0 z-10 bg-white/80 backdrop-blur-md border-b border-secondary-200">
        <div className="max-w-2xl mx-auto px-4 py-4 flex items-center gap-4">
          <button
            onClick={() => navigate(-1)}
            className="p-2 hover:bg-secondary-100 rounded-lg transition-colors"
          >
            <ArrowLeft className="w-5 h-5 text-secondary-600" />
          </button>
          <h1 className="text-lg font-semibold text-secondary-900">个人资料</h1>
        </div>
      </header>

      {/* Content */}
      <main className="max-w-2xl mx-auto px-4 py-6">
        {/* Avatar Section */}
        <div className="bg-white rounded-2xl shadow-sm border border-secondary-200 p-6 mb-4">
          <div className="flex items-center gap-4">
            <div className="w-20 h-20 bg-primary-100 rounded-full flex items-center justify-center">
              <User className="w-10 h-10 text-primary-600" />
            </div>
            <div>
              <h2 className="text-xl font-semibold text-secondary-900">
                {profile?.nickname || '访客用户'}
              </h2>
              <p className="text-sm text-secondary-500">
                {profile?.type === 'REGISTERED' ? '已注册用户' : '匿名访客'}
              </p>
            </div>
          </div>
        </div>

        {/* Profile Info */}
        <div className="bg-white rounded-2xl shadow-sm border border-secondary-200 p-6 mb-4">
          <h3 className="text-sm font-medium text-secondary-500 mb-4">基本信息</h3>

          {/* Nickname */}
          <div className="mb-4">
            <label className="block text-sm font-medium text-secondary-700 mb-1.5">
              昵称
            </label>
            <div className="flex gap-2">
              <input
                type="text"
                value={nickname}
                onChange={(e) => setNickname(e.target.value)}
                placeholder="设置你的昵称"
                className="flex-1 px-4 py-2.5 border border-secondary-200 rounded-lg focus:outline-none focus:ring-2 focus:ring-primary-500/20 focus:border-primary-500"
              />
              <button
                onClick={handleSave}
                disabled={saving || !nickname.trim()}
                className="px-4 py-2.5 bg-primary-600 text-white rounded-lg hover:bg-primary-700 disabled:opacity-50 disabled:cursor-not-allowed flex items-center gap-2"
              >
                {saved ? (
                  <>
                    <Check className="w-4 h-4" />
                    <span>已保存</span>
                  </>
                ) : (
                  <>
                    <Save className="w-4 h-4" />
                    <span>{saving ? '保存中...' : '保存'}</span>
                  </>
                )}
              </button>
            </div>
          </div>

          {/* Phone */}
          <div className="mb-4">
            <label className="block text-sm font-medium text-secondary-700 mb-1.5">
              手机号
            </label>
            <div className="flex items-center gap-3 px-4 py-2.5 bg-secondary-50 rounded-lg">
              <Phone className="w-4 h-4 text-secondary-400" />
              {profile?.phone ? (
                <span className="text-secondary-900">{profile.phone}</span>
              ) : (
                <button
                  onClick={() => navigate('/bind-phone')}
                  className="text-primary-600 hover:text-primary-700"
                >
                  点击绑定手机
                </button>
              )}
            </div>
          </div>

          {/* User ID */}
          <div className="mb-4">
            <label className="block text-sm font-medium text-secondary-700 mb-1.5">
              用户 ID
            </label>
            <div className="flex items-center gap-3 px-4 py-2.5 bg-secondary-50 rounded-lg">
              <Mail className="w-4 h-4 text-secondary-400" />
              <span className="text-secondary-600 font-mono text-sm">
                {profile?.id || userId}
              </span>
            </div>
          </div>

          {/* Created At */}
          <div>
            <label className="block text-sm font-medium text-secondary-700 mb-1.5">
              注册时间
            </label>
            <div className="px-4 py-2.5 bg-secondary-50 rounded-lg text-secondary-600">
              {profile?.createdAt ? formatDate(profile.createdAt) : '未知'}
            </div>
          </div>
        </div>

        {/* Back Button */}
        <button
          onClick={() => navigate('/chat')}
          className="w-full py-3 bg-white border border-secondary-200 rounded-xl text-secondary-700 hover:bg-secondary-50 transition-colors"
        >
          返回对话
        </button>
      </main>
    </div>
  );
}
