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

      // 1. Signup with all details including files
      const signupResult = await signupAction({
        user_type: "agent",
        first_name: sanitizeInput(data.firstName),
        last_name: sanitizeInput(data.lastName),
        email: sanitizeEmail(data.email),
        phone_number: sanitizePhone(data.phone),
        password: data.password,
        office_address: sanitizeInput(data.officeAddress),
        gst_certificate: gstFile,
        msme_certificate: msmeFile,
        business_document: documentFile,
      });

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

      console.log("[Agent Signup] User registered successfully");
      toast.success({
        title: "Agent account created",
        description: "Logging you in...",
      });

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

      if (!loginResult.success || !loginResult.token) {
        toast.warning({
          title: "Please log in",
          description:
            "Account created but auto-login failed. Please log in manually.",
        });
        router.push("/login");
        return;
      }

      storeToken(loginResult.token);

      // Create session data
      const sessionData = {
        email: loginResult.user?.email || data.email,
        name: `${data.firstName} ${data.lastName}`,
        role: "agent",
        officeAddress: data.officeAddress,
        loginTime: new Date().toISOString(),
      };

      sessionStorage.setItem("agent_session", JSON.stringify(sessionData));

      toast.success({
        title: "Setup Complete",
        description: "Welcome to the Ameera Holidays Agent network!",
      });

      router.push("/");
    } catch (error) {
      console.error("[Agent 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="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>
  );
}
