import React, { useState } from 'react'
import { User, userDatabase } from '@/lib/userDatabase'
import { Input } from "@/components/ui/input"
import { Textarea } from "@/components/ui/textarea"
import { Button } from "@/components/ui/button"
import { Avatar, AvatarFallback, AvatarImage } from "@/components/ui/avatar"
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card"

export function 个人资料({ onClose }: { onClose: () => void }) {
  const [user, setUser] = useState<User>({
    id: Date.now(),
    name: '',
    age: 0,
    avatar: '',
    location: '',
    budget: 0,
    bio: '',
    occupation: '',
    travelStyle: '',
    email: '',
    phone: '',
    socialMedia: { instagram: '', website: '' },
    languages: [],
    interests: []
  })
  const [isLoading, setIsLoading] = useState(false)
  const [error, setError] = useState<string | null>(null)

  const handleInputChange = (e: React.ChangeEvent<HTMLInputElement | HTMLTextAreaElement | HTMLSelectElement>) => {
    const { name, value } = e.target
    setUser(prevUser => {
      if (name.startsWith('socialMedia.')) {
        const socialMediaField = name.split('.')[1]
        return { ...prevUser, socialMedia: { ...prevUser.socialMedia, [socialMediaField]: value } }
      }
      return { ...prevUser, [name]: value }
    })
  }

  const handleAvatarUpload = (e: React.ChangeEvent<HTMLInputElement>) => {
    const file = e.target.files?.[0]
    if (file) {
      const reader = new FileReader()
      reader.onloadend = () => {
        setUser(prevUser => ({ ...prevUser, avatar: reader.result as string }))
      }
      reader.readAsDataURL(file)
    }
  }

  const handleSave = async () => {
    setIsLoading(true);
    setError(null);
  
    try {
      const response = await fetch(`/api/users/${user.id}`, {
        method: 'PUT',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify(user),
      });
  
      if (!response.ok) {
        throw new Error('Failed to update user');
      }
  
      const updatedUser = await response.json();
      console.log('Profile updated successfully', updatedUser);
      onClose();
    } catch (error) {
      console.error('Error updating profile:', error);
      setError('更新个人资料失败,请稍后再试。');
    } finally {
      setIsLoading(false);
    }
  };

  return (
    <div className="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50">
      <Card className="max-w-4xl mx-auto overflow-y-auto max-h-[90vh]">
        <CardHeader className="flex justify-between items-center">
          <CardTitle className="text-2xl font-bold">个人资料</CardTitle>
          <Button variant="ghost" onClick={onClose}>X</Button>
        </CardHeader>
        <CardContent>
          <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
            <div className="col-span-2 flex items-center space-x-4">
              <Avatar className="w-24 h-24">
                {user.avatar && <AvatarImage src={user.avatar} alt={user.name} />}
                <AvatarFallback>{user.name[0]}</AvatarFallback>
              </Avatar>
              <Input type="file" accept="image/*" className="w-auto" onChange={handleAvatarUpload} />
            </div>
            <div>
              <label htmlFor="name" className="block text-sm font-medium text-gray-700">姓名</label>
              <Input id="name" name="name" value={user.name} onChange={handleInputChange} />
            </div>
            <div>
              <label htmlFor="age" className="block text-sm font-medium text-gray-700">年龄</label>
              <Input id="age" name="age" type="number" value={user.age} onChange={handleInputChange} />
            </div>
            <div>
              <label htmlFor="location" className="block text-sm font-medium text-gray-700">所在地</label>
              <Input id="location" name="location" value={user.location} onChange={handleInputChange} />
            </div>
            <div>
              <label htmlFor="budget" className="block text-sm font-medium text-gray-700">预算</label>
              <Input id="budget" name="budget" type="number" value={user.budget} onChange={handleInputChange} />
            </div>
            <div className="col-span-2">
              <label htmlFor="bio" className="block text-sm font-medium text-gray-700">个人简介</label>
              <Textarea id="bio" name="bio" value={user.bio} onChange={handleInputChange} />
            </div>
            <div>
              <label htmlFor="occupation" className="block text-sm font-medium text-gray-700">职业</label>
              <Input id="occupation" name="occupation" value={user.occupation} onChange={handleInputChange} />
            </div>
            <div>
              <label htmlFor="travelStyle" className="block text-sm font-medium text-gray-700">旅行风格</label>
              <Input id="travelStyle" name="travelStyle" value={user.travelStyle} onChange={handleInputChange} />
            </div>
            <div>
              <label htmlFor="email" className="block text-sm font-medium text-gray-700">电子邮箱</label>
              <Input id="email" name="email" type="email" value={user.email} onChange={handleInputChange} />
            </div>
            <div>
              <label htmlFor="phone" className="block text-sm font-medium text-gray-700">电话号码</label>
              <Input id="phone" name="phone" value={user.phone} onChange={handleInputChange} />
            </div>
            <div>
              <label htmlFor="socialMedia.instagram" className="block text-sm font-medium text-gray-700">Instagram</label>
              <Input id="socialMedia.instagram" name="socialMedia.instagram" value={user.socialMedia.instagram} onChange={handleInputChange} />
            </div>
            <div>
              <label htmlFor="socialMedia.website" className="block text-sm font-medium text-gray-700">个人网站</label>
              <Input id="socialMedia.website" name="socialMedia.website" value={user.socialMedia.website} onChange={handleInputChange} />
            </div>
            <div className="col-span-2">
              <label htmlFor="languages" className="block text-sm font-medium text-gray-700">语言</label>
              <select
                id="languages"
                name="languages"
                multiple
                value={user.languages}
                onChange={handleInputChange}
                className="w-full p-2 border rounded-md"
              >
                <option value="中文">中文</option>
                <option value="英语">英语</option>
                <option value="日语">日语</option>
                <option value="法语">法语</option>
                <option value="德语">德语</option>
              </select>
            </div>
          </div>
          <Button onClick={handleSave} className="mt-6" disabled={isLoading}>
            {isLoading ? '保存中...' : '保存更改'}
          </Button>
          {error && <p className="text-red-500 mt-2">{error}</p>}
        </CardContent>
      </Card>
    </div>
  )
}