import React, { useState } from 'react';
import { useAuth } from '../../contexts/AuthContext';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
import { Alert, AlertDescription } from '@/components/ui/alert';
import { Avatar, AvatarFallback, AvatarImage } from '@/components/ui/avatar';
import { 
  Dialog,
  DialogContent,
  DialogHeader,
  DialogTitle,
  DialogTrigger,
} from '@/components/ui/dialog';
import { 
  User, 
  Mail, 
  Shield, 
  Save,
  Loader2,
  LogOut
} from 'lucide-react';

export default function UserProfile() {
  const { user, logout, updateUser } = useAuth();
  const [isOpen, setIsOpen] = useState(false);
  const [isLoading, setIsLoading] = useState(false);
  const [message, setMessage] = useState(null);
  const [formData, setFormData] = useState({
    username: user?.username || '',
    // 可以添加更多用户字段
  });

  const handleInputChange = (field, value) => {
    setFormData(prev => ({ ...prev, [field]: value }));
  };

  const handleSaveProfile = async () => {
    setIsLoading(true);
    setMessage(null);
    
    try {
      // 更新用户信息
      const updatedUser = { ...user, ...formData };
      updateUser(updatedUser);
      setMessage({ type: 'success', text: '个人信息更新成功！' });
      setTimeout(() => {
        setIsOpen(false);
        setMessage(null);
      }, 2000);
    } catch (error) {
      setMessage({ type: 'error', text: '更新失败，请稍后重试' });
    } finally {
      setIsLoading(false);
    }
  };

  const handleLogout = async () => {
    try {
      await logout();
    } catch (error) {
      console.error('Logout failed:', error);
    }
  };

  const getUserInitials = (name) => {
    if (!name) return '用';
    return name.charAt(0).toUpperCase();
  };

  return (
    <Dialog open={isOpen} onOpenChange={setIsOpen}>
      <DialogTrigger asChild>
        <div className="flex items-center gap-3 cursor-pointer hover:bg-slate-50 rounded-lg p-2 transition-colors">
          <Avatar className="w-9 h-9">
            <AvatarImage src={user?.avatar_url} alt={user?.username} />
            <AvatarFallback className="bg-gradient-to-br from-slate-400 to-slate-500 text-white text-sm">
              {getUserInitials(user?.username)}
            </AvatarFallback>
          </Avatar>
          <div className="flex-1 min-w-0">
            <p className="font-medium text-slate-900 text-sm truncate">
              {user?.username || '用户'}
            </p>
            <p className="text-xs text-slate-500 truncate">
              {user?.is_admin ? '管理员' : '普通用户'}
            </p>
          </div>
        </div>
      </DialogTrigger>
      
      <DialogContent className="max-w-md">
        <DialogHeader>
          <DialogTitle className="flex items-center gap-2">
            <User className="w-5 h-5" />
            个人信息
          </DialogTitle>
        </DialogHeader>
        
        <div className="space-y-6 py-4">
          {message && (
            <Alert className={message.type === 'error' ? 'border-red-200 bg-red-50 text-red-700' : 'border-green-200 bg-green-50 text-green-700'}>
              <AlertDescription>{message.text}</AlertDescription>
            </Alert>
          )}

          {/* 头像和基本信息 */}
          <div className="flex flex-col items-center gap-4">
            <Avatar className="w-20 h-20">
              <AvatarImage src={user?.avatar_url} alt={user?.username} />
              <AvatarFallback className="bg-gradient-to-br from-blue-500 to-purple-500 text-white text-xl">
                {getUserInitials(user?.username)}
              </AvatarFallback>
            </Avatar>
            <div className="text-center">
              <p className="font-medium text-slate-900">{user?.username}</p>
              {/* <p className="text-sm text-slate-500">用户ID: {user?.id}</p> */}
            </div>
          </div>

          {/* 表单字段 */}
          <div className="space-y-4">
            <div>
              <Label htmlFor="username" className="flex items-center gap-2 text-sm font-medium text-slate-700">
                <User className="w-4 h-4" />
                用户名
              </Label>
              <Input
                id="username"
                value={formData.username}
                onChange={(e) => handleInputChange('username', e.target.value)}
                className="mt-1"
              />
            </div>

            <div>
              <Label className="flex items-center gap-2 text-sm font-medium text-slate-700">
                <Shield className="w-4 h-4" />
                角色
              </Label>
              <Input
                value={user?.is_admin ? '管理员' : '普通用户'}
                disabled
                className="mt-1 bg-slate-50"
              />
            </div>

            <div>
              <Label className="flex items-center gap-2 text-sm font-medium text-slate-700">
                <Mail className="w-4 h-4" />
                注册时间
              </Label>
              <Input
                value={user?.created_at ? new Date(user.created_at).toLocaleString() : '未知'}
                disabled
                className="mt-1 bg-slate-50"
              />
            </div>
          </div>

          {/* 操作按钮 */}
          <div className="flex gap-3 pt-4">
            <Button
              onClick={handleSaveProfile}
              disabled={isLoading}
              className="flex-1 bg-blue-600 hover:bg-blue-700"
            >
              {isLoading ? (
                <>
                  <Loader2 className="w-4 h-4 mr-2 animate-spin" />
                  保存中...
                </>
              ) : (
                <>
                  <Save className="w-4 h-4 mr-2" />
                  保存更改
                </>
              )}
            </Button>
            
            <Button
              onClick={handleLogout}
              variant="outline"
              className="flex-1 text-red-600 hover:text-red-700 hover:bg-red-50"
            >
              <LogOut className="w-4 h-4 mr-2" />
              退出登录
            </Button>
          </div>
        </div>
      </DialogContent>
    </Dialog>
  );
}