"use client"

import { useState, useEffect } from "react"
import { useRouter } from "next/navigation"
import { useForm } from "react-hook-form"
import { zodResolver } from "@hookform/resolvers/zod"
import { loginSchema, type LoginInput } from "@/lib/validations/auth"
import { Button } from "@/components/ui/button"
import { Input } from "@/components/ui/input"
import { Label } from "@/components/ui/label"
import { useToastEnhanced } from "@/hooks/use-toast-enhanced"
import { Loader2, Mail, Lock, Eye, EyeOff } from "lucide-react"
import { userDataStore, defaultCredentials } from "@/lib/data/users"
import { clientRateLimit, clearClientRateLimit } from "@/lib/security/rate-limit"
import { generateClientCsrfToken, verifyClientCsrfToken } from "@/lib/security/client-csrf"
import { sanitizeEmail } from "@/lib/security/sanitize"

export function LoginForm() {
  const [isLoading, setIsLoading] = useState(false)
  const [showPassword, setShowPassword] = useState(false)
  const [csrfToken, setCsrfToken] = useState<string>("")
  const toast = useToastEnhanced()
  const router = useRouter()

  useEffect(() => {
    setCsrfToken(generateClientCsrfToken())
  }, [])

  const {
    register,
    handleSubmit,
    formState: { errors },
  } = useForm<LoginInput>({
    resolver: zodResolver(loginSchema),
  })

  const onSubmit = async (data: LoginInput) => {
    if (!verifyClientCsrfToken(csrfToken)) {
      toast.error({
        title: "Security error",
        description: "Please refresh the page and try again",
      })
      return
    }

    const rateCheck = clientRateLimit("login_attempt", 5, 60000)
    if (!rateCheck.allowed) {
      const waitTime = Math.ceil(rateCheck.resetIn / 1000)
      toast.error({
        title: "Too many attempts",
        description: `Please wait ${waitTime} seconds before trying again`,
      })
      return
    }

    setIsLoading(true)

    try {
      const sanitizedEmail = sanitizeEmail(data.email)

      let userRole: "admin" | "customer" | "agent" | "hotel" | null = null
      let userName = ""

      if (sanitizedEmail === defaultCredentials.admin.email && data.password === defaultCredentials.admin.password) {
        userRole = "admin"
        userName = defaultCredentials.admin.name
      } else if (
        sanitizedEmail === defaultCredentials.customer.email &&
        data.password === defaultCredentials.customer.password
      ) {
        userRole = "customer"
        userName = defaultCredentials.customer.name
      } else if (
        sanitizedEmail === defaultCredentials.agent.email &&
        data.password === defaultCredentials.agent.password
      ) {
        userRole = "agent"
        userName = defaultCredentials.agent.name
      } else if (
        sanitizedEmail === defaultCredentials.hotel.email &&
        data.password === defaultCredentials.hotel.password
      ) {
        userRole = "hotel"
        userName = defaultCredentials.hotel.name
      } else {
        // Check in user data store
        const user = userDataStore.getUserByEmail(sanitizedEmail)
        if (user && user.password === data.password) {
          userRole = user.role
          userName = user.name
        }
      }

      if (!userRole) {
        throw new Error("Invalid email or password")
      }

      clearClientRateLimit("login_attempt")

      // Store session based on role
      const sessionData = {
        email: sanitizedEmail,
        name: userName,
        role: userRole,
        loginTime: new Date().toISOString(),
      }

      if (userRole === "admin") {
        sessionStorage.setItem("admin_session", JSON.stringify(sessionData))
        const cookieValue = encodeURIComponent(JSON.stringify(sessionData))
        document.cookie = `admin_session=${cookieValue}; path=/; max-age=86400; SameSite=Strict${window.location.protocol === "https:" ? "; Secure" : ""}`

        toast.success({
          title: "Welcome back, Admin!",
          description: "Redirecting to dashboard...",
        })

        router.push("/admin/dashboard")
      } else if (userRole === "customer") {
        sessionStorage.setItem("customer_session", JSON.stringify(sessionData))

        window.dispatchEvent(new Event("sessionUpdate"))

        toast.success({
          title: `Welcome back, ${userName}!`,
          description: "You have successfully logged in.",
        })

        router.push("/user/dashboard")
      } else if (userRole === "agent") {
        sessionStorage.setItem("agent_session", JSON.stringify(sessionData))
        // Set cookie for agent session
        const cookieValue = encodeURIComponent(JSON.stringify(sessionData))
        document.cookie = `agent_session=${cookieValue}; path=/; max-age=86400; SameSite=Strict${window.location.protocol === "https:" ? "; Secure" : ""}`

        toast.success({
          title: `Welcome back, ${userName}!`,
          description: "Redirecting to agent dashboard...",
        })

        router.push("/agent/dashboard")
      } else if (userRole === "hotel") {
        sessionStorage.setItem("hotel_session", JSON.stringify(sessionData))
        // Set cookie for hotel session
        const cookieValue = encodeURIComponent(JSON.stringify(sessionData))
        document.cookie = `hotel_session=${cookieValue}; path=/; max-age=86400; SameSite=Strict${window.location.protocol === "https:" ? "; Secure" : ""}`

        toast.success({
          title: `Welcome back, ${userName}!`,
          description: "Redirecting to hotel dashboard...",
        })

        router.push("/hotel/dashboard")
      }
    } catch (error) {
      toast.error({
        title: "Login failed",
        description: error instanceof Error ? error.message : "Please check your credentials",
      })
    } finally {
      setIsLoading(false)
    }
  }

  return (
    <form onSubmit={handleSubmit(onSubmit)} className="space-y-4">
      <input type="hidden" name="csrf_token" value={csrfToken} />

      <div className="space-y-2">
        <Label htmlFor="login-email">Email address</Label>
        <div className="relative">
          <Mail className="absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground" aria-hidden="true" />
          <Input
            id="login-email"
            type="email"
            placeholder="your@email.com"
            autoComplete="email"
            disabled={isLoading}
            className="pl-10"
            aria-invalid={errors.email ? "true" : "false"}
            aria-describedby={errors.email ? "login-email-error" : undefined}
            {...register("email")}
          />
        </div>
        {errors.email && (
          <p id="login-email-error" className="text-sm text-destructive" role="alert">
            {errors.email.message}
          </p>
        )}
      </div>

      <div className="space-y-2">
        <Label htmlFor="login-password">Password</Label>
        <div className="relative">
          <Lock className="absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground" aria-hidden="true" />
          <Input
            id="login-password"
            type={showPassword ? "text" : "password"}
            placeholder="Enter your password"
            autoComplete="current-password"
            disabled={isLoading}
            className="pl-10 pr-10"
            aria-invalid={errors.password ? "true" : "false"}
            aria-describedby={errors.password ? "login-password-error" : undefined}
            {...register("password")}
          />
          <Button
            type="button"
            variant="ghost"
            size="sm"
            className="absolute right-1 top-1/2 -translate-y-1/2 h-8 w-8 p-0"
            onClick={() => setShowPassword(!showPassword)}
            aria-label={showPassword ? "Hide password" : "Show password"}
          >
            {showPassword ? (
              <EyeOff className="h-4 w-4" aria-hidden="true" />
            ) : (
              <Eye className="h-4 w-4" aria-hidden="true" />
            )}
          </Button>
        </div>
        {errors.password && (
          <p id="login-password-error" className="text-sm text-destructive" role="alert">
            {errors.password.message}
          </p>
        )}
      </div>

      <Button type="submit" className="w-full" size="lg" disabled={isLoading} aria-label="Sign in to your account">
        {isLoading && <Loader2 className="mr-2 h-4 w-4 animate-spin" aria-hidden="true" />}
        {isLoading ? "Signing in..." : "Sign In"}
      </Button>
    </form>
  )
}
