"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 { agentSignupSchema, type AgentSignupInput } from "@/lib/validations/auth"
import { Button } from "@/components/ui/button"
import { Input } from "@/components/ui/input"
import { Label } from "@/components/ui/label"
import { Textarea } from "@/components/ui/textarea"
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 AgentSignupForm() {
  const [isLoading, setIsLoading] = useState(false)
  const [gstFile, setGstFile] = useState<File | null>(null)
  const [msmeFile, setMsmeFile] = useState<File | null>(null)
  const [documentFile, setDocumentFile] = useState<File | null>(null)
  const [csrfToken, setCsrfToken] = useState<string>("")
  const toast = useToastEnhanced()
  const router = useRouter()

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

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

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

    const rateCheck = clientRateLimit("agent_signup_attempt", 5, 300000)
    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 sanitizedAddress = sanitizeInput(data.officeAddress)

      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: "agent",
        isVerified: true,
      })

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

      toast.success({
        title: "Agent account created",
        description: "Welcome to the Teertham Agent network!",
      })

      router.push("/")
    } 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="agent-firstName">First Name</Label>
          <Input
            id="agent-firstName"
            type="text"
            placeholder="Jane"
            autoComplete="given-name"
            disabled={isLoading}
            aria-invalid={errors.firstName ? "true" : "false"}
            aria-describedby={errors.firstName ? "agent-firstName-error" : undefined}
            {...register("firstName")}
          />
          {errors.firstName && (
            <p id="agent-firstName-error" className="text-sm text-destructive" role="alert">
              {errors.firstName.message}
            </p>
          )}
        </div>

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

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

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

      <div className="space-y-2">
        <Label htmlFor="agent-gst">GST Certificate</Label>
        <div className="relative">
          <Input
            id="agent-gst"
            type="file"
            accept=".pdf,.jpg,.jpeg,.png"
            disabled={isLoading}
            className="cursor-pointer"
            onChange={(e) => setGstFile(e.target.files?.[0] || null)}
          />
          {gstFile && <p className="text-xs text-muted-foreground mt-1">Selected: {gstFile.name}</p>}
        </div>
        <p className="text-xs text-muted-foreground">Upload GST certificate (PDF, JPG, PNG)</p>
      </div>

      <div className="space-y-2">
        <Label htmlFor="agent-msme">MSME Certificate</Label>
        <div className="relative">
          <Input
            id="agent-msme"
            type="file"
            accept=".pdf,.jpg,.jpeg,.png"
            disabled={isLoading}
            className="cursor-pointer"
            onChange={(e) => setMsmeFile(e.target.files?.[0] || null)}
          />
          {msmeFile && <p className="text-xs text-muted-foreground mt-1">Selected: {msmeFile.name}</p>}
        </div>
        <p className="text-xs text-muted-foreground">Upload MSME certificate (PDF, JPG, PNG)</p>
      </div>

      <div className="space-y-2">
        <Label htmlFor="agent-address">Office Address</Label>
        <Textarea
          id="agent-address"
          placeholder="Enter your complete office address"
          disabled={isLoading}
          rows={3}
          aria-invalid={errors.officeAddress ? "true" : "false"}
          aria-describedby={errors.officeAddress ? "agent-address-error" : undefined}
          {...register("officeAddress")}
        />
        {errors.officeAddress && (
          <p id="agent-address-error" className="text-sm text-destructive" role="alert">
            {errors.officeAddress.message}
          </p>
        )}
      </div>

      <div className="space-y-2">
        <Label htmlFor="agent-document">Visiting Card or Other Document</Label>
        <div className="relative">
          <Input
            id="agent-document"
            type="file"
            accept=".pdf,.jpg,.jpeg,.png"
            disabled={isLoading}
            className="cursor-pointer"
            onChange={(e) => setDocumentFile(e.target.files?.[0] || null)}
          />
          {documentFile && <p className="text-xs text-muted-foreground mt-1">Selected: {documentFile.name}</p>}
        </div>
        <p className="text-xs text-muted-foreground">Upload visiting card or other business document</p>
      </div>

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