import React, { useState } from "react"
import { useNavigate, Link } from "react-router-dom"
import { Button } from "../components/ui/button"
import { Input } from "../components/ui/input"
import { SettingsMenu } from "../components/SettingsMenu"
import { ArrowLeft, ArrowRight, Command, Loader2, Eye, EyeOff } from "lucide-react"
import { toast } from "sonner"
import { useTranslation } from "../hooks/useTranslation"
import { loginWithPassword, sendOtp, loginWithOtp } from "../api/users"

type AuthStep = "mobile" | "password" | "otp"
type AuthMode = "login" | "register"

export default function Auth() {
  const navigate = useNavigate()
  const { t, lang } = useTranslation()
  const isRtl = lang === "fa"
  
  const [step, setStep] = useState<AuthStep>("mobile")
  const [mode, setMode] = useState<AuthMode>("login")
  const [mobile, setMobile] = useState("")
  const [password, setPassword] = useState("")
  const [otpCode, setOtpCode] = useState("")
  const [loading, setLoading] = useState(false)
  const [showPassword, setShowPassword] = useState(false) // Added state for password visibility

  const handleTokenResponse = (access: string, refresh: string) => {
    localStorage.setItem("accessToken", access)
    localStorage.setItem("refreshToken", refresh)
    toast.success(t.login.toasts.successLogin)
    navigate("/profile")
  }

  const handleSendOtp = async (selectedMode: AuthMode) => {
    if (!mobile) return toast.error(t.login.toasts.enterMobile)
    setLoading(true)
    
    try {
      await sendOtp(mobile, selectedMode)
      setMode(selectedMode)
      setStep("otp")
      toast.success(t.login.toasts.verifySent)
    } catch (err: any) {
      toast.error(t.login.toasts.failedOtp)
    } finally {
      setLoading(false)
    }
  }

  const handlePasswordLogin = async (e: React.FormEvent) => {
    e.preventDefault()
    if (!mobile || !password) return toast.error(t.login.toasts.fillAll)
    setLoading(true)

    try {
      const data = await loginWithPassword(mobile, password)
      handleTokenResponse(data.access, data.refresh)
    } catch (err: any) {
      toast.error(t.login.toasts.invalidCreds)
    } finally {
      setLoading(false)
    }
  }

  const handleOtpVerify = async (e: React.FormEvent) => {
    e.preventDefault()
    if (!mobile || !otpCode) return toast.error(t.login.toasts.enterOtp)
    setLoading(true)

    try {
      const data = await loginWithOtp(mobile, otpCode)
      handleTokenResponse(data.access, data.refresh)
    } catch (err: any) {
      toast.error(t.login.toasts.invalidOtp)
    } finally {
      setLoading(false)
    }
  }

  const BackIcon = isRtl ? ArrowRight : ArrowLeft

  return (
    <div className="container relative min-h-screen flex-col items-center justify-center grid lg:max-w-none lg:grid-cols-2 lg:px-0 bg-white dark:bg-slate-950 transition-colors">
      
      <div className="absolute inset-e-4 top-4 z-50 md:inset-e-8 md:top-8">
        <SettingsMenu />
      </div>

      <div className="relative hidden h-full flex-col bg-slate-900 dark:bg-slate-900/50 p-10 text-white lg:flex border-e border-slate-200 dark:border-slate-800">
        <div className="relative z-20 flex items-center text-lg font-medium gap-2">
          <Command className="h-6 w-6" />
          {t.title || "Qlockify"}
        </div>
        <div className="relative z-20 mt-auto">
          <blockquote className="space-y-2">
            <p className="text-lg">"{t.login.brandingQuote}"</p>
          </blockquote>
        </div>
      </div>

      <div className="p-8 lg:p-8 flex h-screen items-center justify-center">
        <div className="mx-auto flex w-full flex-col justify-center space-y-6 sm:w-87.5">
          
          <div className="flex flex-col space-y-2 text-center text-slate-900 dark:text-slate-50">
            <div className="flex justify-center lg:hidden mb-4">
              <Command className="h-8 w-8" />
            </div>
            <h1 className="text-2xl font-semibold tracking-tight">
              {step === "mobile" && t.login.welcome(t.title)}
              {step === "password" && t.login.enterPassword}
              {step === "otp" && t.login.verifyNumber}
            </h1>
            <p className="text-sm text-slate-500 dark:text-slate-400">
              {step === "mobile" && t.login.enterMobileDesc}
              {step === "password" && t.login.signInDesc}
              {step === "otp" && t.login.sentCodeDesc(mobile)}
            </p>
          </div>

          <div className="grid gap-6">
            {step === "mobile" && (
              <div className="grid gap-4">
                <Input
                  id="mobile"
                  placeholder={t.login.mobilePlaceholder}
                  type="tel"
                  dir="ltr"
                  value={mobile}
                  onChange={(e) => setMobile(e.target.value)}
                  maxLength={11}
                  disabled={loading}
                  className={`h-11 ${isRtl ? "text-end" : "text-start"}`}
                />
                <Button onClick={() => { if (!mobile) return toast.error(t.login.toasts.enterMobile); setStep("password") }} className="w-full h-11">
                  {t.login.continueWithPassword}
                </Button>

                <div className="relative">
                  <div className="absolute inset-0 flex items-center">
                    <span className="w-full border-t border-slate-200 dark:border-slate-800" />
                  </div>
                  <div className="relative flex justify-center text-xs uppercase">
                    <span className="bg-white dark:bg-slate-950 px-2 text-slate-500 dark:text-slate-400 transition-colors">
                      {t.login.orContinueWith}
                    </span>
                  </div>
                </div>

                <div className="grid grid-cols-2 gap-4">
                  <Button variant="outline" onClick={() => handleSendOtp("login")} disabled={loading} className="h-11">
                    {loading && mode === "login" && <Loader2 className="me-2 h-4 w-4 animate-spin" />}
                    {t.login.otpLogin}
                  </Button>
                  <Button variant="outline" onClick={() => handleSendOtp("register")} disabled={loading} className="h-11">
                    {loading && mode === "register" && <Loader2 className="me-2 h-4 w-4 animate-spin" />}
                    {t.login.register}
                  </Button>
                </div>
              </div>
            )}

            {step === "password" && (
              <form onSubmit={handlePasswordLogin} autoComplete="off" className="grid gap-4">
                <div className="relative w-full" dir="ltr">
                  <Input
                    id="password"
                    placeholder={t.login.passwordPlaceholder}
                    type={showPassword ? "text" : "password"}
                    autoComplete="new-password"
                    dir="ltr"
                    name="some-random-name-to-disable-auto-complete-on-browser"
                    value={password}
                    onChange={(e) => setPassword(e.target.value)}
                    disabled={loading}
                    className={`h-11 pr-10 ${isRtl ? "text-end" : "text-start"}`}
                  />
                  <button
                    type="button"
                    tabIndex={-1}
                    onClick={() => setShowPassword((prev) => !prev)}
                    className="absolute inset-y-0 right-0 flex items-center pr-3 text-slate-500 hover:text-slate-700 dark:text-slate-400 dark:hover:text-slate-300"
                  >
                    {showPassword ? <EyeOff size={18} /> : <Eye size={18} />}
                  </button>
                </div>
                <Button type="submit" className="w-full h-11" disabled={loading}>
                  {loading && <Loader2 className="me-2 h-4 w-4 animate-spin" />} {t.login.signIn}
                </Button>
                <Button type="button" variant="ghost" onClick={() => setStep("mobile")} className="text-sm text-slate-500 dark:text-slate-400">
                  <BackIcon className="me-2 h-4 w-4" /> {t.login.back}
                </Button>
              </form>
            )}

            {step === "otp" && (
              <form onSubmit={handleOtpVerify} className="grid gap-4">
                <Input
                  id="otp"
                  placeholder={t.login.otpPlaceholder}
                  type="text"
                  dir="ltr"
                  value={otpCode}
                  onChange={(e) => setOtpCode(e.target.value)}
                  maxLength={6}
                  disabled={loading}
                  className="h-11 text-center tracking-widest text-lg"
                />
                <Button type="submit" className="w-full h-11" disabled={loading}>
                  {loading && <Loader2 className="me-2 h-4 w-4 animate-spin" />} {t.login.verifyAndContinue}
                </Button>
                <Button type="button" variant="ghost" onClick={() => setStep("mobile")} className="text-sm text-slate-500 dark:text-slate-400">
                  <BackIcon className="me-2 h-4 w-4" /> {t.login.back}
                </Button>
              </form>
            )}
          </div>

          <div className="mt-6 text-center text-sm text-slate-500 dark:text-slate-400">
            {t.loginTerms?.prefix}
            <Link 
              to="/terms" 
              className="font-medium text-blue-600 hover:text-blue-500 dark:text-blue-400 dark:hover:text-blue-300 transition-colors"
            >
              {t.loginTerms?.link}
            </Link>
            {t.loginTerms?.suffix}
          </div>

        </div>
      </div>
    </div>
  )
}
