import { zodResolver } from "@hookform/resolvers/zod"
import { EyeIcon, EyeOffIcon } from "lucide-react"
import { useEffect, useState } from "react"
import { Controller, useForm } from "react-hook-form"
import { Link, useLocation, useNavigate } from "react-router-dom"
import { toast } from "sonner"
import { z } from "zod"
import { apiLogin, apiRegister } from "@/api/auth"
import { Button } from "@/components/ui/button"
import { Card, CardContent } from "@/components/ui/card"
import { Checkbox } from "@/components/ui/checkbox"
import { FieldError } from "@/components/ui/field"
import { Input } from "@/components/ui/input"
import { cn } from "@/lib/utils"
import bg from "./_assets/bg.webp"

const loginSchema = z.object({
  account: z.string().trim().min(1, "请输入账号"),
  password: z.string().min(1, "请输入密码"),
  remember: z.boolean(),
})

type LoginValues = z.infer<typeof loginSchema>

const registerSchema = z.object({
  phone: z.string().regex(/^1\d{10}$/, "请输入正确的手机号"),
  smsCode: z.string().min(3, "请输入短信验证码").max(6, "请输入短信验证码"),
  password: z.string().trim().min(1, "请输入密码"),
  wx: z.string(),
  qq: z.string(),
  agreed: z.boolean().refine(v => v, "请先阅读并同意用户协议和隐私政策"),
})

type RegisterValues = z.infer<typeof registerSchema>

export default function LoginPage() {
  const [tab, setTab] = useState<"login" | "register">("login")
  const location = useLocation()

  useEffect(() => {
    const initTab = location.state?.tab
    if (initTab === "login" || initTab === "register") {
      setTab(initTab)
    }
  }, [location.state])

  return (
    <main
      className={cn(
        "relative",
        "h-screen w-screen xl:pr-64 bg-cover bg-left",
        "flex justify-center xl:justify-end items-center",
      )}
      style={{ backgroundImage: `url(${bg})` }}
    >
      <Card className="w-96 mx-4 shadow-lg relative z-20 py-8">
        <CardContent className="px-8">
          <div className="flex mb-6 rounded-lg bg-gray-100 p-1">
            <Button
              variant="ghost"
              onClick={() => setTab("login")}
              className={`flex-1 py-2 rounded-md transition-all ${
                tab === "login"
                  ? "bg-white shadow-sm text-blue-600 font-medium"
                  : "text-gray-600 hover:text-gray-900"
              }`}
            >
              登录
            </Button>
            <Button
              variant="ghost"
              onClick={() => setTab("register")}
              className={`flex-1 py-2 rounded-md transition-all ${
                tab === "register"
                  ? "bg-white shadow-sm text-blue-600 font-medium"
                  : "text-gray-600 hover:text-gray-900"
              }`}
            >
              注册
            </Button>
          </div>
          {tab === "login" ? (
            <LoginForm />
          ) : (
            <RegisterForm onSwitchToLogin={() => setTab("login")} />
          )}
        </CardContent>
      </Card>
    </main>
  )
}

function LoginForm() {
  const navigate = useNavigate()
  const [showPassword, setShowPassword] = useState(false)
  const [submitting, setSubmitting] = useState(false)

  const form = useForm<LoginValues>({
    resolver: zodResolver(loginSchema),
    defaultValues: {
      account: "",
      password: "",
      remember: false,
    },
  })

  const onSubmit = async (data: LoginValues) => {
    setSubmitting(true)
    try {
      const resp = await apiLogin({
        logincode: data.account,
        password: data.password,
      })

      if (resp.success) {
        toast.success("登录成功", {
          description: "欢迎回来！",
        })
        navigate("/")
      } else {
        toast.error(resp.message || "登录失败")
      }
    } catch {
      toast.error("网络错误，请重试")
    } finally {
      setSubmitting(false)
    }
  }

  return (
    <form className="space-y-4" onSubmit={form.handleSubmit(onSubmit)}>
      <div className="space-y-1">
        <label htmlFor="account" className="text-sm font-medium text-gray-700">
          会员号
        </label>
        <Controller
          name="account"
          control={form.control}
          render={({ field, fieldState }) => (
            <>
              <Input
                id="account"
                type="text"
                placeholder="请输入会员号"
                className="w-full"
                {...field}
              />
              <FieldError>{fieldState.error?.message}</FieldError>
            </>
          )}
        />
      </div>
      <div className="space-y-1">
        <label htmlFor="password" className="text-sm font-medium text-gray-700">
          密码
        </label>
        <Controller
          name="password"
          control={form.control}
          render={({ field, fieldState }) => (
            <>
              <div className="relative">
                <Input
                  id="password"
                  type={showPassword ? "text" : "password"}
                  placeholder="请输入密码"
                  className="w-full pr-10"
                  {...field}
                />
                <button
                  type="button"
                  className="absolute right-3 top-1/2 -translate-y-1/2 text-gray-400 hover:text-gray-600"
                  onClick={() => setShowPassword(!showPassword)}
                  tabIndex={-1}
                >
                  {showPassword ? (
                    <EyeOffIcon className="size-4" />
                  ) : (
                    <EyeIcon className="size-4" />
                  )}
                </button>
              </div>
              <FieldError>{fieldState.error?.message}</FieldError>
            </>
          )}
        />
      </div>
      <div className="flex items-center justify-between text-sm">
        <div className="flex items-center space-x-2">
          <Controller
            name="remember"
            control={form.control}
            render={({ field }) => (
              <Checkbox
                id="remember"
                checked={field.value}
                onCheckedChange={field.onChange}
              />
            )}
          />
          <label htmlFor="remember" className="text-gray-600 cursor-pointer">
            记住密码
          </label>
        </div>
        <Link
          to="/login"
          state={{ tab: "register" }}
          className="text-blue-600 hover:text-blue-700 text-xs"
        >
          忘记密码?
        </Link>
      </div>
      <Button
        type="submit"
        className="w-full bg-blue-600 hover:bg-blue-700 text-white"
        disabled={submitting}
      >
        {submitting ? "登录中..." : "登录"}
      </Button>
      <p className="text-center text-xs text-gray-400 mt-2">
        手机号不是IP账号，请登陆后开通IP账号
      </p>
    </form>
  )
}

function RegisterForm({ onSwitchToLogin }: { onSwitchToLogin: () => void }) {
  const [smsCountdown, setSmsCountdown] = useState(0)
  const [smsLoading, setSmsLoading] = useState(false)
  const [showPassword, setShowPassword] = useState(false)
  const [submitting, setSubmitting] = useState(false)

  const form = useForm<RegisterValues>({
    resolver: zodResolver(registerSchema),
    defaultValues: {
      phone: "",
      smsCode: "",
      password: "",
      wx: "",
      qq: "",
      agreed: false,
    },
  })

  const handleSendSMS = async () => {
    const valid = await form.trigger("phone")
    if (!valid) return

    setSmsLoading(true)
    try {
      const { sendSMS } = await import("@/api/verify")
      const resp = await sendSMS(form.getValues("phone"), "User_Code")
      if (!resp.success) {
        throw new Error(resp.message || "短信发送失败")
      }

      let countdown = 60
      setSmsCountdown(countdown)
      const timer = setInterval(() => {
        countdown -= 1
        if (countdown <= 0) {
          clearInterval(timer)
          setSmsCountdown(0)
        } else {
          setSmsCountdown(countdown)
        }
      }, 1000)

      toast.success("验证码已发送")
    } catch (e) {
      toast.error("验证码发送失败", {
        description: (e as Error).message,
      })
    } finally {
      setSmsLoading(false)
    }
  }

  const onSubmit = async (data: RegisterValues) => {
    setSubmitting(true)
    try {
      const resp = await apiRegister({
        phone: data.phone,
        password: data.password,
        code: data.smsCode,
        wx: data.wx,
        qq: data.qq,
      })

      if (resp.success) {
        toast.success("注册成功，请登录")
        onSwitchToLogin()
      } else {
        toast.error(resp.message || "注册失败")
      }
    } catch {
      toast.error("网络错误，请重试")
    } finally {
      setSubmitting(false)
    }
  }

  return (
    <form className="space-y-4" onSubmit={form.handleSubmit(onSubmit)}>
      <div className="space-y-1">
        <label
          htmlFor="reg-account"
          className="text-sm font-medium text-gray-700"
        >
          手机号
        </label>
        <Controller
          name="phone"
          control={form.control}
          render={({ field, fieldState }) => (
            <>
              <Input
                id="reg-account"
                type="text"
                placeholder="请输入手机号码"
                className="w-full"
                {...field}
              />
              <FieldError>{fieldState.error?.message}</FieldError>
            </>
          )}
        />
      </div>
      <div className="space-y-1">
        <label htmlFor="reg-sms" className="text-sm font-medium text-gray-700">
          短信验证码
        </label>
        <div className="flex items-start gap-2">
          <Controller
            name="smsCode"
            control={form.control}
            render={({ field, fieldState }) => (
              <div className="flex-1 space-y-1">
                <Input
                  id="reg-sms"
                  type="text"
                  placeholder="请输入短信验证码"
                  className="h-10"
                  maxLength={6}
                  autoComplete="one-time-code"
                  {...field}
                  onChange={e =>
                    field.onChange(e.target.value.replace(/\D/g, ""))
                  }
                />
                <FieldError>{fieldState.error?.message}</FieldError>
              </div>
            )}
          />
          <Button
            type="button"
            variant="outline"
            className="h-10 w-28 shrink-0 whitespace-nowrap"
            onClick={handleSendSMS}
            disabled={smsCountdown > 0 || smsLoading}
          >
            {smsLoading
              ? "发送中..."
              : smsCountdown > 0
                ? `${smsCountdown}秒后重发`
                : "获取验证码"}
          </Button>
        </div>
      </div>
      <div className="space-y-1">
        <label
          htmlFor="reg-password"
          className="text-sm font-medium text-gray-700"
        >
          请输入密码
        </label>
        <Controller
          name="password"
          control={form.control}
          render={({ field, fieldState }) => (
            <>
              <div className="relative">
                <Input
                  id="reg-password"
                  type={showPassword ? "text" : "password"}
                  placeholder="请输入密码"
                  className="w-full pr-10"
                  {...field}
                />
                <button
                  type="button"
                  className="absolute right-3 top-1/2 -translate-y-1/2 text-gray-400 hover:text-gray-600"
                  onClick={() => setShowPassword(!showPassword)}
                  tabIndex={-1}
                >
                  {showPassword ? (
                    <EyeIcon className="size-4" />
                  ) : (
                    <EyeOffIcon className="size-4" />
                  )}
                </button>
              </div>
              <FieldError>{fieldState.error?.message}</FieldError>
            </>
          )}
        />
      </div>
      <div className="space-y-1">
        <label htmlFor="reg-wx" className="text-sm font-medium text-gray-700">
          微信号
          <span className="text-gray-400 font-normal text-xs ml-1">(选填)</span>
        </label>
        <Controller
          name="wx"
          control={form.control}
          render={({ field }) => (
            <Input
              id="reg-wx"
              type="text"
              placeholder="请输入微信号"
              className="w-full"
              {...field}
            />
          )}
        />
      </div>
      <div className="space-y-1">
        <label htmlFor="reg-qq" className="text-sm font-medium text-gray-700">
          QQ号
          <span className="text-gray-400 font-normal text-xs ml-1">(选填)</span>
        </label>
        <Controller
          name="qq"
          control={form.control}
          render={({ field }) => (
            <Input
              id="reg-qq"
              type="text"
              placeholder="请输入QQ号"
              className="w-full"
              {...field}
              onChange={e => field.onChange(e.target.value.replace(/\D/g, ""))}
            />
          )}
        />
      </div>
      <div className="space-y-1">
        <Controller
          name="agreed"
          control={form.control}
          render={({ field, fieldState }) => (
            <>
              <div className="flex items-center space-x-2">
                <Checkbox
                  id="agreement"
                  checked={field.value}
                  onCheckedChange={field.onChange}
                />
                <label
                  htmlFor="agreement"
                  className="text-xs text-gray-600 cursor-pointer"
                >
                  我同意
                  <a
                    href="/xieyi.html"
                    className="text-blue-600 hover:text-blue-500"
                    target="_blank"
                    rel="noopener"
                  >
                    《聚IP JUIP.COM用户注册协议》
                  </a>
                </label>
              </div>
              <FieldError>{fieldState.error?.message}</FieldError>
            </>
          )}
        />
      </div>
      <Button
        type="submit"
        className="w-full bg-blue-600 hover:bg-blue-700 text-white"
        disabled={submitting}
      >
        {submitting ? "提交中..." : "首次登录即注册"}
      </Button>
      <p className="text-center text-xs text-gray-400 mt-2">
        已有账号?
        <button
          type="button"
          className="text-blue-600 hover:text-blue-700 ml-1"
          onClick={onSwitchToLogin}
        >
          立即登录
        </button>
      </p>
    </form>
  )
}
