﻿"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 { clientRateLimit } from "@/core/security/rate-limit";
import {
  generateClientCsrfToken,
  verifyClientCsrfToken,
} from "@/core/security/client-csrf";
import {
  sanitizeEmail,
  sanitizeInput,
  sanitizePhone,
} from "@/core/security/sanitize";
import {
  signupAction,
  loginAction,
} from "@/features/auth/actions/auth-api-actions";
import { storeToken } from "@/core/api/client/axios-client";

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 {
      console.log("[Customer Signup] Starting signup process");

      // Call backend API via server action
      const signupResult = await signupAction({
        user_type: "customer",
        first_name: sanitizeInput(data.firstName),
        last_name: sanitizeInput(data.lastName),
        email: sanitizeEmail(data.email),
        phone_number: sanitizePhone(data.phone),
        password: data.password,
      });

      console.log("[Customer Signup] Signup API response", {
        success: signupResult.success,
        hasUser: !!signupResult.user,
      });

      if (!signupResult.success) {
        throw new Error(signupResult.error || "Signup failed");
      }

      if (!signupResult.user) {
        throw new Error("Invalid response from server");
      }

      console.log("[Customer Signup] User registered successfully", {
        email: data.email,
      });

      toast.success({
        title: "Account created successfully",
        description: "Logging you in...",
      });

      // Auto-login after successful signup
      console.log("[Customer Signup] Auto-login initiated");
      const loginResult = await loginAction({
        email: data.email,
        password: data.password,
      });

      if (!loginResult.success || !loginResult.user) {
        // Signup succeeded but login failed - redirect to login page
        toast.info({
          title: "Please log in",
          description: "Your account was created. Please log in to continue.",
        });
        router.replace("/login");
        return;
      }

      // Store token in localStorage for client-side axios requests
      if (loginResult.token) {
        console.log("[Customer Signup] Storing token in localStorage");
        storeToken(loginResult.token);
      }

      // Create session data
      const fullName = [
        loginResult.user.first_name,
        loginResult.user.last_name,
      ]
        .filter(Boolean)
        .join(" ")
        .trim();
      const sessionData = {
        userId: loginResult.user.id ? String(loginResult.user.id) : undefined,
        email: loginResult.user.email,
        name: fullName || loginResult.user.name || data.email.split("@")[0],
        role: "customer",
        loginTime: new Date().toISOString(),
      };

      const serializedSession = JSON.stringify(sessionData);
      sessionStorage.setItem("customer_session", serializedSession);
      localStorage.setItem("customer_session", serializedSession);
      window.dispatchEvent(new Event("sessionUpdate"));

      router.replace("/user/dashboard");
    } catch (error) {
      console.log("[Customer Signup] Error:", 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>
  );
}
