import { useSession, signOut, user } from '../../lib/auth-client'
import {
  Avatar,
  Button,
  Card,
  Input,
  Form,
  TextField,
  Label,
  FieldError,
  toast,
} from '@heroui/react'
import { useState, useEffect } from 'react'
import { useNavigate } from 'react-router-dom'

export default function ProfilePage() {
  const { data: session, isPending } = useSession()
  const navigate = useNavigate()
  const [name, setName] = useState('')
  const [isEditing, setIsEditing] = useState(false)
  const [loading, setLoading] = useState(false)

  useEffect(() => {
    if (session?.user) {
      setName(session.user.name || '')
    } else if (!isPending && !session) {
      navigate('/login')
    }
  }, [session, isPending, navigate])

  if (isPending || !session) {
    return (
      <div className="flex min-h-[calc(100vh-64px)] items-center justify-center">
        加载中...
      </div>
    )
  }

  const handleUpdateProfile = async (e: React.FormEvent<HTMLFormElement>) => {
    e.preventDefault()
    setLoading(true)
    try {
      await user.update({
        name,
      })
      toast.success('个人信息更新成功')
      setIsEditing(false)
    } catch (err) {
      console.error(err)
      toast.danger('更新失败')
    } finally {
      setLoading(false)
    }
  }

  return (
    <div className="flex min-h-[calc(100vh-64px)] flex-col items-center justify-center p-4">
      <Card className="w-full max-w-2xl">
        <Card.Header>
          <Card.Title className="text-2xl font-bold">个人资料</Card.Title>
        </Card.Header>
        <Card.Content className="flex flex-col gap-8 md:flex-row">
          <div className="flex flex-col items-center gap-4">
            <Avatar className="h-32 w-32 text-4xl" color="accent">
              <Avatar.Image
                src={session.user.image || ''}
                alt={session.user.name || 'User'}
              />
              <Avatar.Fallback>
                {(session.user.name || 'U').slice(0, 2).toUpperCase()}
              </Avatar.Fallback>
            </Avatar>
            <Button
              variant="outline"
              color="danger"
              onPress={() => signOut()}
              fullWidth
            >
              退出登录
            </Button>
          </div>

          <div className="flex-1 space-y-6">
            <Form validationBehavior="native" onSubmit={handleUpdateProfile}>
              <div className="space-y-4">
                <TextField isReadOnly>
                  <Label>邮箱</Label>
                  <Input value={session.user.email} variant="flat" />
                </TextField>

                <TextField
                  name="name"
                  value={name}
                  onChange={setName}
                  isReadOnly={!isEditing}
                >
                  <Label>昵称</Label>
                  <Input variant={isEditing ? 'secondary' : 'flat'} />
                  <FieldError />
                </TextField>

                <TextField isReadOnly>
                  <Label>用户ID</Label>
                  <Input value={session.user.id} variant="flat" />
                </TextField>
              </div>

              <div className="mt-6 flex justify-end gap-3">
                {isEditing ? (
                  <>
                    <Button
                      type="button"
                      variant="ghost"
                      onPress={() => {
                        setIsEditing(false)
                        setName(session.user.name || '')
                      }}
                      isDisabled={loading}
                    >
                      取消
                    </Button>
                    <Button type="submit" isPending={loading}>
                      保存修改
                    </Button>
                  </>
                ) : (
                  <Button
                    type="button"
                    variant="solid"
                    onPress={() => setIsEditing(true)}
                  >
                    编辑资料
                  </Button>
                )}
              </div>
            </Form>
          </div>
        </Card.Content>
      </Card>
    </div>
  )
}
