"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 { customerSignupSchema, type CustomerSignupInput } 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 } from "lucide-react"
import { userDataStore } from "@/lib/data/users"
import { clientRateLimit } from "@/lib/security/rate-limit"
import { generateClientCsrfToken, verifyClientCsrfToken } from "@/lib/security/client-csrf"
import { sanitizeEmail, sanitizeInput, sanitizePhone } from "@/lib/security/sanitize"

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

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

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

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

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

    setIsLoading(true)

    try {
      const sanitizedEmail = sanitizeEmail(data.email)
      const sanitizedFirstName = sanitizeInput(data.firstName)
      const sanitizedLastName = sanitizeInput(data.lastName)
      const sanitizedPhone = sanitizePhone(data.phone)

      const existingUser = userDataStore.getUserByEmail(sanitizedEmail)
      if (existingUser) {
        throw new Error("An account with this email already exists")
      }

      const fullName = `${sanitizedFirstName} ${sanitizedLastName}`
      const newUser = userDataStore.createUser({
        name: fullName,
        email: sanitizedEmail,
        phone: sanitizedPhone,
        password: data.password,
        role: "customer",
        isVerified: true,
      })

      sessionStorage.setItem(
        "customer_session",
        JSON.stringify({
          userId: newUser.id,
          email: newUser.email,
          name: newUser.name,
          role: newUser.role,
        }),
      )

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

      toast.success({
        title: "Account created successfully",
        description: "Welcome to Teertham!",
      })

      router.push("/user/dashboard")
    } catch (error) {
      toast.error({
        title: "Signup failed",
        description: error instanceof Error ? error.message : "Please try again",
      })
    } finally {
      setIsLoading(false)
    }
  }

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

      <div className="grid grid-cols-2 gap-4">
        <div className="space-y-2">
          <Label htmlFor="customer-firstName">First Name</Label>
          <Input
            id="customer-firstName"
            type="text"
            placeholder="John"
            autoComplete="given-name"
            disabled={isLoading}
            aria-invalid={errors.firstName ? "true" : "false"}
            aria-describedby={errors.firstName ? "customer-firstName-error" : undefined}
            {...register("firstName")}
          />
          {errors.firstName && (
            <p id="customer-firstName-error" className="text-sm text-destructive" role="alert">
              {errors.firstName.message}
            </p>
          )}
        </div>

        <div className="space-y-2">
          <Label htmlFor="customer-lastName">Last Name</Label>
          <Input
            id="customer-lastName"
            type="text"
            placeholder="Doe"
            autoComplete="family-name"
            disabled={isLoading}
            aria-invalid={errors.lastName ? "true" : "false"}
            aria-describedby={errors.lastName ? "customer-lastName-error" : undefined}
            {...register("lastName")}
          />
          {errors.lastName && (
            <p id="customer-lastName-error" className="text-sm text-destructive" role="alert">
              {errors.lastName.message}
            </p>
          )}
        </div>
      </div>

      <div className="space-y-2">
        <Label htmlFor="customer-signup-email">Email</Label>
        <Input
          id="customer-signup-email"
          type="email"
          placeholder="john@example.com"
          autoComplete="email"
          disabled={isLoading}
          aria-invalid={errors.email ? "true" : "false"}
          aria-describedby={errors.email ? "customer-signup-email-error" : undefined}
          {...register("email")}
        />
        {errors.email && (
          <p id="customer-signup-email-error" className="text-sm text-destructive" role="alert">
            {errors.email.message}
          </p>
        )}
      </div>

      <div className="space-y-2">
        <Label htmlFor="customer-signup-phone">Phone Number</Label>
        <Input
          id="customer-signup-phone"
          type="tel"
          placeholder="+91 9876543210"
          autoComplete="tel"
          disabled={isLoading}
          aria-invalid={errors.phone ? "true" : "false"}
          aria-describedby={errors.phone ? "customer-phone-error" : undefined}
          {...register("phone")}
        />
        {errors.phone && (
          <p id="customer-phone-error" className="text-sm text-destructive" role="alert">
            {errors.phone.message}
          </p>
        )}
      </div>

      <div className="space-y-2">
        <Label htmlFor="customer-signup-password">Password</Label>
        <Input
          id="customer-signup-password"
          type="password"
          placeholder="Create a strong password"
          autoComplete="new-password"
          disabled={isLoading}
          aria-invalid={errors.password ? "true" : "false"}
          aria-describedby={errors.password ? "customer-signup-password-error" : undefined}
          {...register("password")}
        />
        {errors.password && (
          <p id="customer-signup-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="Create customer account">
        {isLoading && <Loader2 className="mr-2 h-4 w-4 animate-spin" aria-hidden="true" />}
        {isLoading ? "Creating account..." : "Create Customer Account"}
      </Button>
    </form>
  )
}
