import { EyeIcon, EyeOffIcon } from "lucide-react"
import { useEffect, useState } from "react"
import { Link, useLocation, useNavigate } from "react-router-dom"
import { toast } from "sonner"
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 { Input } from "@/components/ui/input"
import { cn } from "@/lib/utils"
import bg from "./_assets/bg.webp"

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 [account, setAccount] = useState("")
  const [password, setPassword] = useState("")
  const [showPassword, setShowPassword] = useState(false)
  const [remember, setRemember] = useState(false)
  const [submitting, setSubmitting] = useState(false)

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault()
    if (!account.trim()) {
      toast.error("请输入账号")
      return
    }
    if (!password) {
      toast.error("请输入密码")
      return
    }
    setSubmitting(true)
    try {
      const resp = await apiLogin({
        logincode: account,
        password,
      })
      console.log(resp, "resp")

      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={handleSubmit}>
      <div className="space-y-1">
        <label htmlFor="account" className="text-sm font-medium text-gray-700">
          会员号
        </label>
        <Input
          id="account"
          type="text"
          placeholder="请输入会员号"
          className="w-full"
          value={account}
          onChange={e => setAccount(e.target.value)}
        />
      </div>
      <div className="space-y-1">
        <label htmlFor="password" className="text-sm font-medium text-gray-700">
          密码
        </label>
        <div className="relative">
          <Input
            id="password"
            type={showPassword ? "text" : "password"}
            placeholder="请输入密码"
            className="w-full pr-10"
            value={password}
            onChange={e => setPassword(e.target.value)}
          />
          <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>
      </div>
      <div className="flex items-center justify-between text-sm">
        <div className="flex items-center space-x-2">
          <Checkbox
            id="remember"
            checked={remember}
            onCheckedChange={v => setRemember(!!v)}
          />
          <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 [phone, setPhone] = useState("")
  const [smsCode, setSmsCode] = useState("")
  const [smsCountdown, setSmsCountdown] = useState(0)
  const [smsLoading, setSmsLoading] = useState(false)
  const [newPassword, setNewPassword] = useState("")
  const [showPassword, setShowPassword] = useState(false)
  const [wx, setWx] = useState("")
  const [qq, setQq] = useState("")
  const [agreed, setAgreed] = useState(false)
  const [submitting, setSubmitting] = useState(false)

  const handleSendSMS = async () => {
    if (!/^1\d{10}$/.test(phone)) {
      toast.error("请输入正确的手机号")
      return
    }

    setSmsLoading(true)
    try {
      const { sendSMS } = await import("@/api/verify")
      const resp = await sendSMS(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 handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault()

    if (!/^1\d{10}$/.test(phone)) {
      toast.error("请输入正确的手机号")
      return
    }
    if (smsCode.length < 3 || smsCode.length > 6) {
      toast.error("请输入短信验证码")
      return
    }
    if (!newPassword.trim()) {
      toast.error("请输入密码")
      return
    }
    if (!agreed) {
      toast.error("请先阅读并同意用户协议和隐私政策")
      return
    }

    setSubmitting(true)
    try {
      const resp = await apiRegister({
        phone,
        password: newPassword,
        code: smsCode,
        wx,
        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={handleSubmit}>
      <div className="space-y-1">
        <label
          htmlFor="reg-account"
          className="text-sm font-medium text-gray-700"
        >
          手机号
        </label>
        <Input
          id="reg-account"
          type="text"
          placeholder="请输入手机号码"
          className="w-full"
          value={phone}
          onChange={e => setPhone(e.target.value)}
        />
      </div>
      <div className="space-y-1">
        <label htmlFor="reg-sms" className="text-sm font-medium text-gray-700">
          短信验证码
        </label>
        <div className="flex gap-2">
          <Input
            id="reg-sms"
            type="text"
            placeholder="请输入短信验证码"
            className="h-10"
            maxLength={6}
            autoComplete="one-time-code"
            value={smsCode}
            onChange={e => setSmsCode(e.target.value.replace(/\D/g, ""))}
          />
          <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>
        <div className="relative">
          <Input
            id="reg-password"
            type={showPassword ? "text" : "password"}
            placeholder="请输入密码"
            className="w-full pr-10"
            value={newPassword}
            onChange={e => setNewPassword(e.target.value)}
          />
          <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>
      </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>
        <Input
          id="reg-wx"
          type="text"
          placeholder="请输入微信号"
          className="w-full"
          value={wx}
          onChange={e => setWx(e.target.value)}
        />
      </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>
        <Input
          id="reg-qq"
          type="text"
          placeholder="请输入QQ号"
          className="w-full"
          value={qq}
          onChange={e => setQq(e.target.value.replace(/\D/g, ""))}
        />
      </div>
      <div className="flex items-center space-x-2">
        <Checkbox
          id="agreement"
          checked={agreed}
          onCheckedChange={v => setAgreed(!!v)}
        />
        <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>
      <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>
  )
}
