"use client"

import * as React from "react"
import { useState, useEffect, useRef } from "react"
import { z } from "zod"
import { useForm } from "react-hook-form"
import { zodResolver } from "@hookform/resolvers/zod"
import { Form, FormField, FormItem, FormLabel, FormControl, FormMessage } from "@/components/ui/form"
import { Input } from "@/components/ui/input"
import { Button } from "@/components/ui/button"
import { Eye, EyeOff, ArrowLeft, ArrowRight, Calendar, Mic } from "lucide-react"
import Link from "next/link"
import Image from "next/image"
import { cn } from "@/lib/utils"
import LoginSlideOneImg from "@/assets/images/loginSlideOne.png"
import LoginSlideTwoImg from "@/assets/images/loginSlideTwo.png"
import LoginSlideThreeImg from "@/assets/images/loginSlideThree.png"
import { useSignIn, useSignUp } from "@/lib/react-query/hooks/auth"
import { SignUpPayload, LoginPayload } from "@/types/auth"
import { useRouter } from "next/navigation"
import { PasswordStrengthInput } from "@/components/password-strength-input"
import Autocomplete from "react-google-autocomplete"
import { useTranslations } from "next-intl"
import { LanguageSwitcher } from "@/components/ui/language-switcher"
import { useLocale } from "next-intl"
import { useNotification } from "@/context/NotificationProvider"

type AuthMode = "signup" | "login"

interface AuthPageProps {
  mode: AuthMode
}

export default function Auth({ mode }: AuthPageProps) {
  const t = useTranslations('auth')
  const tf = useTranslations('features')
  const tv = useTranslations('validation')
  const locale = useLocale()
  const { token: fcmToken } = useNotification()

  const [showPassword, setShowPassword] = useState(false)
  const [currentFeature, setCurrentFeature] = useState(0)
  const [fadeState, setFadeState] = useState("fade-in")
  const [signupSuccess, setSignupSuccess] = useState(false)
  const slideIntervalRef = useRef<NodeJS.Timeout | null>(null)

  const signUpMutation = useSignUp()
  const signInMutation = useSignIn()
  const router = useRouter()

  const signupSchema = z.object({
    email: z.string().email(tv('invalidEmail')),
    name: z.string().min(2, tv('nameRequired')),
    password: z.string()
      .min(6, tv('passwordTooShort'))
      .regex(/[a-z]/, tv('passwordLowercase'))
      .regex(/[A-Z]/, tv('passwordUppercase'))
      .regex(/\d/, tv('passwordNumber'))
      .regex(/[!@#$%^&*()_+\-=\[\]{};':"\\|,.<>\/?]/, tv('passwordSpecial')),
    address: z.string().min(3, tv('required'))
  })

  const loginSchema = z.object({
    email: z.string().email(tv('invalidEmail')),
    password: z.string().min(6, tv('passwordTooShort'))
  })

  type SignupValues = z.infer<typeof signupSchema>
  type LoginValues = z.infer<typeof loginSchema>

  const passwordStrengthTranslations = {
    veryWeak: tv('passwordStrength.veryWeak'),
    weak: tv('passwordStrength.weak'),
    fair: tv('passwordStrength.fair'),
    good: tv('passwordStrength.good'),
    strong: tv('passwordStrength.strong'),
    lowercase: tv('passwordStrength.lowercase'),
    uppercase: tv('passwordStrength.uppercase'),
    number: tv('passwordStrength.number'),
    special: tv('passwordStrength.special'),
    minLength: tv('passwordStrength.minLength')
  }

  const features = [
    {
      title: tf('aiVoiceAssistant.title'),
      description: tf('aiVoiceAssistant.description'),
      image: LoginSlideOneImg,
      icon: Mic
    },
    {
      title: tf('appointmentCalendar.title'),
      description: tf('appointmentCalendar.description'),
      image: LoginSlideTwoImg,
      icon: Calendar
    },
    {
      title: tf('customerRecords.title'),
      description: tf('customerRecords.description'),
      image: LoginSlideThreeImg,
      icon: Calendar
    }
  ]

  const form = useForm<SignupValues | LoginValues>({
    resolver: zodResolver(mode === "signup" ? signupSchema : loginSchema),
    defaultValues: mode === "signup" ? { email: "", name: "", password: "", address: "" } : { email: "", password: "" }
  })

  const onSubmit = async (values: SignupValues | LoginValues) => {
    if (mode === "signup") {
      // Map name to name for payload
      const payload: SignUpPayload = {
        name: (values as SignupValues).name,
        email: (values as SignupValues).email,
        password: (values as SignupValues).password,
        address: (values as SignupValues).address,
        timezone: Intl.DateTimeFormat().resolvedOptions().timeZone,
        fcmToken: fcmToken || undefined
      }

      await signUpMutation.mutateAsync(payload)
      setSignupSuccess(true)
    } else {
      const payload: LoginPayload = {
        email: (values as LoginValues).email,
        password: (values as LoginValues).password,
        fcmToken: fcmToken || undefined
      }
      await signInMutation.mutateAsync(payload)
    }
  }

  // Animation config
  const ANIMATION_DURATION = 400
  const AUTOPLAY_DELAY = 4000

  // Carousel logic
  const goToFeature = (idx: number) => {
    setFadeState("fade-out")
    setTimeout(() => {
      setCurrentFeature(idx)
      setFadeState("fade-in")
    }, ANIMATION_DURATION)
  }

  const nextFeature = () => goToFeature((currentFeature + 1) % features.length)
  const prevFeature = () => goToFeature((currentFeature - 1 + features.length) % features.length)

  useEffect(() => {
    slideIntervalRef.current = setInterval(nextFeature, AUTOPLAY_DELAY)
    return () => {
      if (slideIntervalRef.current) clearInterval(slideIntervalRef.current)
    }
  }, [currentFeature])

  const CurrentIcon = features[currentFeature].icon

  return (
    <div className="min-h-screen w-full flex flex-col lg:flex-row bg-white overflow-hidden">
      {/* LEFT SIDE - FORM */}
      <div className="flex-1 flex flex-col justify-center items-center px-4 py-8 sm:px-8 lg:px-24 relative">
        {/* Language Switcher */}
        <div className="absolute top-4 right-4">
          <LanguageSwitcher />
        </div>
        <div className="w-full max-w-xl">
          {/* LOGO + TITLE */}
          <div className="flex flex-col items-center gap-3 mb-6">
            <Link href="/" className="flex items-center">
              <Image src="/aivly-logo.svg" alt="Company Logo" width={200} height={50} priority />
            </Link>
            <h1 className="text-[26px] sm:text-[32px] font-semibold text-foreground text-center">
              {mode === "signup" ? t('createAccount') : t('welcomeBack')}
            </h1>
          </div>

          {/* FORM OR SUCCESS MESSAGE */}
          {mode === "signup" && signupSuccess ? (
            <div className="text-center space-y-6">
              <div className="w-16 h-16 bg-green-100 rounded-full flex items-center justify-center mx-auto">
                <svg className="w-8 h-8 text-green-600" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                  <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M5 13l4 4L19 7" />
                </svg>
              </div>
              <div>
                <h2 className="text-2xl font-semibold text-gray-900 mb-2">Account Created Successfully!</h2>
                <p className="text-gray-600 mb-4">
                  We've sent a verification email to your email address. Please check your email and click the verification link to activate your account.
                </p>
                {/* <p className="text-sm text-gray-500">
                  Didn't receive the email? Check your spam folder or{" "}
                  <button className="text-primary hover:underline font-medium">
                    resend verification email
                  </button>
                </p> */}
              </div>
              <div className="pt-4">
                <Link href="/sign-in">
                  <Button className="w-full h-12 sm:h-14 text-lg font-medium bg-primary-gradient hover:opacity-90">
                    Go to Login
                  </Button>
                </Link>
              </div>
            </div>
          ) : (
            <Form {...form}>
              <form
                onSubmit={form.handleSubmit(onSubmit)}
                // onSubmit={(e)=> {e.preventDefault(); router.push('/dashboard')}}
                className="space-y-5 sm:space-y-6"
              >
                <FormField
                  control={form.control}
                  name="email"
                  render={({ field }) => (
                    <FormItem>
                      <FormLabel>{t('email')}</FormLabel>
                      <FormControl>
                        <Input placeholder={t('email')} {...field} className="h-12 sm:h-14 text-base" />
                      </FormControl>
                      <FormMessage />
                    </FormItem>
                  )}
                />

                {mode === "signup" && (
                  <>
                    <FormField
                      control={form.control}
                      name="name"
                      render={({ field }) => (
                        <FormItem>
                          <FormLabel>{t('salonName')}</FormLabel>
                          <FormControl>
                            <Input placeholder={t('salonName')} {...field} className="h-12 sm:h-14 text-base" />
                          </FormControl>
                          <FormMessage />
                        </FormItem>
                      )}
                    />
                    <FormField
                      control={form.control}
                      name="address"
                      render={({ field }) => (
                        <FormItem>
                          <FormLabel>{t('address')}</FormLabel>
                          <FormControl>
                            <Autocomplete
                              apiKey={process.env.NEXT_PUBLIC_GOOGLE_MAPS_API_KEY}
                              onPlaceSelected={(place) => {
                                // Set the formatted address to the form
                                if (place?.formatted_address) {
                                  field.onChange(place.formatted_address)
                                }
                              }}
                              options={{
                                types: ["address"],
                                fields: ["formatted_address", "address_components", "geometry"]
                              }}
                              placeholder={t('address')}
                              className="flex h-12 sm:h-14 w-full rounded-md border border-input bg-white px-3 py-2 text-base ring-offset-background file:border-0 file:bg-transparent file:text-sm file:font-medium placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50"
                              defaultValue={field.value}
                              onChange={(e: any) => field.onChange(e.target.values)}
                            />
                          </FormControl>
                          <FormMessage />
                        </FormItem>
                      )}
                    />
                  </>
                )}

                <FormField
                  control={form.control}
                  name="password"
                  render={({ field, fieldState }) => (
                    <FormItem>
                      <FormLabel>{t('password')}</FormLabel>
                      <FormControl>
                        {mode === "signup" ? (
                          <PasswordStrengthInput
                            value={field.value}
                            onChange={field.onChange}
                            placeholder={t('password')}
                            className={fieldState?.error ? "border-destructive focus-visible:ring-destructive/40" : ""}
                            translations={passwordStrengthTranslations}
                          />
                        ) : (
                          <div className="relative">
                            <Input
                              type={showPassword ? "text" : "password"}
                              placeholder={t('password')}
                              {...field}
                              className={cn(
                                "h-12 sm:h-14 text-base pr-12 w-full",
                                fieldState?.error && "border-destructive focus-visible:ring-destructive/40"
                              )}
                            />
                            <button
                              type="button"
                              onClick={() => setShowPassword(!showPassword)}
                              className="absolute right-4 top-1/2 -translate-y-1/2 text-gray-500"
                            >
                              {showPassword ? <Eye className="w-5 h-5" /> : <EyeOff className="w-5 h-5" />}
                            </button>
                          </div>
                        )}
                      </FormControl>
                      <FormMessage />
                      {mode === "login" && (
                        <div className="text-right pt-1">
                          <Link href={`/${locale}/forgot-password`} className="text-sm text-primary hover:underline">
                            {t('forgotPassword')}
                          </Link>
                        </div>
                      )}
                    </FormItem>
                  )}
                />

                <div className="pt-4 space-y-5">
                  <Button disabled={signInMutation.isPending || signUpMutation.isPending} type="submit" className="w-full h-12 sm:h-14 text-lg font-medium bg-primary-gradient hover:opacity-90">
                    {mode === "signup" ? t('signUp') : t('signIn')}
                  </Button>

                  <p className="text-center text-base text-gray-600">
                    {mode === "signup" ? (
                      <>
                        {t('alreadyHaveAccount')}{" "}
                        <Link href={`/${locale}/sign-in`} className="font-semibold text-primary underline">
                          {t('login')}
                        </Link>
                      </>
                    ) : (
                      <>
                        {t('dontHaveAccount')}{" "}
                        <Link href={`/${locale}/sign-up`} className="font-semibold text-primary underline">
                          {t('signUp')}
                        </Link>
                      </>
                    )}
                  </p>
                </div>
              </form>
            </Form>
          )}
        </div>
      </div>

      <div className="hidden lg:flex flex-1 bg-primary-gradient rounded-l-[60px] relative overflow-hidden">
        {/* Background Pattern */}
        {/* <div className="absolute inset-0 opacity-40">
          <Image
            src="https://api.builder.io/api/v1/image/assets/TEMP/eb74035c14f4d1e10598f40584db6236e4efb24f?width=1440"
            alt="pattern"
            fill
            className="object-cover w-full h-full"
          />
        </div> */}

        {/* Carousel Container */}
        <div className="relative z-10 flex flex-col items-center justify-center w-full h-full p-8">
          <div className="relative w-[90%] max-w-md bg-white rounded-2xl  shadow-lg">
            {/* Unified Image + Text Section */}
            <div className="flex flex-col">
              <div className="relative w-full rounded-tl-2xl rounded-tr-2xl overflow-hidden lg:h-[402px]">
                <Image src={features[currentFeature].image} alt={features[currentFeature].title} fill className="object-cover" priority />
              </div>

              <div className="flex items-center gap-4 p-6">
                <div className="w-14 h-14 rounded-lg bg-primary-gradient flex items-center justify-center shrink-0">
                  <CurrentIcon className="w-8 h-8 text-white" />
                </div>
                <div>
                  <h3 className="text-lg font-semibold text-gray-900">{features[currentFeature].title}</h3>
                  <p className="text-sm text-gray-600">{features[currentFeature].description}</p>
                </div>
              </div>
            </div>

            {/* Navigation Arrows (edges, vertically centered) */}
            <div className="absolute inset-y-0 left-0 right-0 flex items-center justify-between pointer-events-none">
              <Button
                onClick={prevFeature}
                className="pointer-events-auto w-[54px] h-[54px] rounded-full bg-white hover:bg-gray-100 shadow-md -ml-6"
              >
                <ArrowLeft size={42} className="text-gradient-start" />
              </Button>
              <Button
                onClick={nextFeature}
                className="pointer-events-auto  w-[54px] h-[54px] rounded-full bg-white hover:bg-gray-100 shadow-md -mr-6"
              >
                <ArrowRight size={42} className="text-gradient-start" />
              </Button>
            </div>
          </div>

          {/* Dots */}
          <div className="flex items-center justify-center gap-2 mt-6">
            {features.map((_, i) => (
              <button
                key={i}
                onClick={() => goToFeature(i)}
                className={`rounded-full transition-all duration-300 ${i === currentFeature ? "w-8 h-3 bg-white shadow-md" : "w-3 h-3 bg-white/60 hover:bg-white/80"
                  }`}
              />
            ))}
          </div>
        </div>
      </div>
    </div>
  )
}
