import { createFileRoute, useNavigate } from '@tanstack/react-router'
import { useState, useEffect, useRef } from 'react'
import { useForm, Controller } from 'react-hook-form'
import { useAuth } from '../lib/auth-context'
import { trpc } from '../lib/trpc-client'
import { useGetEssentialConsts } from '../hooks/prominent-api-hooks'
import { p, MyButton, pInput as PInput, div } from 'web-components'

export const Route = createFileRoute('/login')({ component: LoginPage })

interface LoginFormInputs {
  mobile: string
  otp?: string
  password?: string
}

function LoginPage() {
  const { loginWithToken } = useAuth()
  const navigate = useNavigate()
  const { data: constsData } = useGetEssentialConsts()
  const [step, setStep] = useState<'mobile' | 'choice' | 'otp' | 'password'>('mobile')
  const [selectedMobile, setSelectedMobile] = useState('')
  const [canResend, setCanResend] = useState(false)
  const [resendCountdown, setResendCountdown] = useState(0)
  const intervalRef = useRef<ReturnType<typeof setInterval>>(null)
  const [otpCells, setOtpCells] = useState(['', '', '', ''])
  const inputRefs = useRef<(HTMLInputElement | null)[]>([null, null, null, null])

  const loginMutation = trpc.user.auth.login.useMutation()
  const sendOtpMutation = trpc.user.auth.sendOtp.useMutation({
    onSuccess: (data) => {
      if (data.success) {
        setResendCountdown(120)
        setCanResend(false)
        setStep('otp')
      }
    },
  })
  const verifyOtpMutation = trpc.user.auth.verifyOtp.useMutation({
    onSuccess: (data) => {
      if (data.success && data.token && data.user) {
        loginWithToken(data.token, data.user)
        navigate({ to: '/home' })
      }
    },
  })

  useEffect(() => {
    return () => {
      if (intervalRef.current) clearInterval(intervalRef.current)
    }
  }, [])

  useEffect(() => {
    if (intervalRef.current) clearInterval(intervalRef.current)
    if (resendCountdown > 0) {
      intervalRef.current = setInterval(() => {
        setResendCountdown((prev) => {
          if (prev <= 1) {
            setCanResend(true)
            return 0
          }
          return prev - 1
        })
      }, 1000)
    }
    return () => {
      if (intervalRef.current) clearInterval(intervalRef.current)
    }
  }, [resendCountdown])

  const { control, handleSubmit, setValue, clearErrors, setError } =
    useForm<LoginFormInputs>({
      defaultValues: { mobile: '', otp: '', password: '' },
    })

  const validateMobile = (mobile: string) => {
    const clean = mobile.replace(/\D/g, '')
    return clean.length === 10 && /^[6-9]/.test(clean)
  }

  const handleOtpChange = (index: number, text: string) => {
    if (text.length > 1) {
      const digits = text.replace(/\D/g, '').slice(0, 4)
      const newCells = digits.split('').concat(['', '', '', '']).slice(0, 4)
      setOtpCells(newCells)
      setValue('otp', newCells.join(''))
      const lastIndex = Math.min(digits.length - 1, 3)
      inputRefs.current[lastIndex]?.focus()
      return
    }
    const newCells = [...otpCells]
    newCells[index] = text
    setOtpCells(newCells)
    setValue('otp', newCells.join(''))
    if (text && index < 3) inputRefs.current[index + 1]?.focus()
    else if (!text && index > 0) inputRefs.current[index - 1]?.focus()
  }

  const onSubmit = (data: LoginFormInputs) => {
    if (step === 'mobile') {
      const mobile = data.mobile.trim()
      if (!validateMobile(mobile)) {
        setError('mobile', { message: 'Enter a valid 10-digit mobile number' })
        return
      }
      setSelectedMobile(mobile.replace(/\D/g, ''))
      sendOtpMutation.mutate({ mobile })
    } else if (step === 'otp') {
      if (!data.otp || data.otp.length < 4) {
        setError('otp', { message: 'Enter a valid OTP' })
        return
      }
      verifyOtpMutation.mutate({ mobile: selectedMobile, otp: data.otp })
    } else if (step === 'password') {
      loginMutation.mutate(
        { identifier: selectedMobile, password: data.password! },
        {
          onSuccess: (res) => {
            loginWithToken(res.data.token, res.data.user)
            navigate({ to: '/home' })
          },
        }
      )
    }
  }

  return (
    <div className="flex min-h-screen items-center justify-center bg-gradient-to-b from-brand-400 to-brand-700 p-4">
      <div className="w-full max-w-md">
        <p className="font-bold mb-2 text-center text-4xl text-white">
          Welcome
        </p>
        <p className="mb-8 text-center text-lg text-blue-100">
          Sign in to continue your journey
        </p>

        <div className="rounded-2xl bg-white p-8 shadow-xl">
          <form onSubmit={handleSubmit(onSubmit)}>
            {step === 'mobile' && (
              <Controller
                control={control}
                name="mobile"
                render={({ field: { onChange, value } }) => (
                  <PInput
                    placeholder="Enter your mobile number"
                    value={value}
                    onChange={(e) => {
                      const clean = e.target.value.replace(/\D/g, '')
                      if (clean.length <= 10) onChange(clean)
                    }}
                    className="bg-gray-50"
                  />
                )}
              />
            )}

            {step === 'otp' && (
              <div className="mb-6">
                <p className="font-semibold mb-3 text-center text-base text-gray-800">
                  Enter 4-digit OTP
                </p>
                <div className="flex justify-center gap-2">
                  {[0, 1, 2, 3].map((i) => (
                    <input
                      key={i}
                      ref={(el) => { inputRefs.current[i] = el }}
                      className="h-14 w-14 rounded-xl border-2 text-center text-2xl font-bold"
                      style={{
                        borderColor: otpCells[i] ? '#E63946' : '#E5E7EB',
                        backgroundColor: otpCells[i] ? '#FFF5F6' : '#F9FAFB',
                      }}
                      type="text"
                      inputMode="numeric"
                      maxLength={1}
                      value={otpCells[i]}
                      onChange={(e) => handleOtpChange(i, e.target.value)}
                    />
                  ))}
                </div>
                <div className="mt-4 flex items-center justify-between border-t border-gray-100 pt-4">
                  <div
                    onClick={() => { setStep('choice'); setOtpCells(['', '', '', '']) }}
                  >
                    <p className="font-medium text-gray-500">Back</p>
                  </div>
                  <button
                    onClick={() => sendOtpMutation.mutate({ mobile: selectedMobile })}
                    disabled={!canResend}
                  >
                    <p
                      className={`font-semibold ${canResend ? 'text-brand-600' : 'text-gray-400'}`}
                    >
                      {canResend ? 'Resend OTP' : `Resend in ${resendCountdown}s`}
                    </p>
                  </button>
                </div>
              </div>
            )}

            {step === 'password' && (
              <Controller
                control={control}
                name="password"
                render={({ field: { onChange, value } }) => (
                  <PInput
                    placeholder="Enter your password"
                    value={value}
                    onChange={(e) => onChange(e.target.value)}
                    type="password"
                    className="bg-gray-50"
                  />
                )}
              />
            )}

            <div className="mt-6">
              <MyButton
                type="submit"
                fullWidth
                className="h-12 rounded-xl bg-brand-600 text-white shadow-lg"
                disabled={
                  sendOtpMutation.isPending ||
                  verifyOtpMutation.isPending ||
                  loginMutation.isPending
                }
                textContent={
                  step === 'otp'
                    ? 'Verify & Login'
                    : step === 'password'
                      ? 'Login'
                      : 'Continue'
                }
              />
            </div>
          </form>

          {step === 'otp' && (
            <div
              onClick={() => { setStep('password'); setOtpCells(['', '', '', '']) }}
              className="mt-4 block text-center"
            >
              <p className="font-semibold text-brand-600">
                Or login with Password
              </p>
            </div>
          )}
        </div>

        {/* Download App Banner */}
        <div className="mt-6 rounded-xl bg-gradient-to-r from-brand-500 to-brand-600 p-4 shadow-lg">
          <div className="flex items-center justify-between">
            <div className="flex-1">
              <p className="text-lg font-bold text-white">Get the FreshYo App</p>
              <p className="text-sm text-white/80 mt-1">Download for exclusive offers & faster checkout</p>
            </div>
            <a
              href={constsData?.playStoreUrl || '#'}
              target="_blank"
              rel="noopener noreferrer"
              className="flex items-center gap-2 rounded-lg bg-white px-4 py-2 text-sm font-bold text-brand-600 shadow-md hover:bg-gray-50 transition-colors"
            >
              <svg className="h-5 w-5" viewBox="0 0 24 24" fill="currentColor">
                <path d="M3 20.5V3.5C3 2.91 3.34 2.39 3.84 2.15L13.69 12L3.84 21.85C3.34 21.6 3 21.09 3 20.5ZM16.81 15.12L6.05 21.34L14.54 12.85L16.81 15.12ZM20.16 10.81C20.5 11.08 20.75 11.5 20.75 12C20.75 12.5 20.53 12.9 20.18 13.18L17.89 14.5L15.39 12L17.89 9.5L20.16 10.81ZM6.05 2.66L16.81 8.88L14.54 11.15L6.05 2.66Z"/>
              </svg>
              Get App
            </a>
          </div>
        </div>
      </div>
    </div>
  )
}
