"use client"

import { Button } from "@/components/ui/button"
import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogHeader,
  DialogTitle,
} from "@/components/ui/dialog"
import { Input } from "@/components/ui/input"
import { Label } from "@/components/ui/label"
import { login as loginApi } from "@/lib/api"
import { toApiError } from "@/lib/errors"
import { notifyInfo } from "@/lib/toast"
import { useAuthStore } from "@/store/auth"
import { useLoginDialogStore } from "@/store/login-dialog"
import { standardSchemaResolver } from "@hookform/resolvers/standard-schema"
import { useRouter } from "next/navigation"
import { useForm } from "react-hook-form"
import { z } from "zod"

const loginSchema = z.object({
  username: z.string().min(1, "请输入用户名"),
  password: z.string().min(6, "密码至少6位"),
})

interface LoginDialogProps {
  open: boolean
  onOpenChange: (open: boolean) => void
}

export function LoginDialog({ open, onOpenChange }: LoginDialogProps) {
  const router = useRouter()
  const { login: storeLogin } = useAuthStore()
  const consumePendingAction = useLoginDialogStore((state) => state.consumePendingAction)
  const {
    register,
    handleSubmit,
    formState: { errors, isSubmitting },
  } = useForm({
    resolver: standardSchemaResolver(loginSchema),
  })

  const onSubmit = async (data: z.infer<typeof loginSchema>) => {
    try {
      const user = await loginApi({ username: data.username, password: data.password })
      storeLogin(user, user.verifiedRoles)
      consumePendingAction()
      onOpenChange(false)
    } catch (err) {
      notifyInfo(toApiError(err).msg)
    }
  }

  return (
    <Dialog open={open} onOpenChange={onOpenChange}>
      <DialogContent className="sm:max-w-md">
        <DialogHeader>
          <DialogTitle>登录聚玩</DialogTitle>
          <DialogDescription>请先登录以继续操作</DialogDescription>
        </DialogHeader>
        <form onSubmit={handleSubmit(onSubmit)} className="space-y-4">
          <div className="space-y-2">
            <Label htmlFor="dialog-username">用户名</Label>
            <Input id="dialog-username" placeholder="请输入用户名" {...register("username")} />
            {errors.username && (
              <p className="text-xs text-destructive">{errors.username.message}</p>
            )}
          </div>
          <div className="space-y-2">
            <Label htmlFor="dialog-password">密码</Label>
            <Input
              id="dialog-password"
              type="password"
              placeholder="请输入密码"
              {...register("password")}
            />
            {errors.password && (
              <p className="text-xs text-destructive">{errors.password.message}</p>
            )}
          </div>
          <div className="flex gap-2">
            <Button type="submit" className="flex-1" disabled={isSubmitting}>
              {isSubmitting ? "登录中..." : "登录"}
            </Button>
            <Button
              type="button"
              variant="outline"
              className="flex-1"
              onClick={() => {
                onOpenChange(false)
                router.push("/register")
              }}
            >
              注册
            </Button>
          </div>
        </form>
      </DialogContent>
    </Dialog>
  )
}
