"use client";

import { useEffect, useState } from "react";
import { useRouter } from "next/navigation";
import LeadFormDialog from "./LeadFormDialog";
import { toast } from "sonner";
import { apiCall } from "@/utils/callApi";

export default function LeadGate() {
  const [open, setOpen] = useState(false);
  const [loading, setLoading] = useState(false);

  const [formData, setFormData] = useState({
    name: "",
    phone_number: "",
    // state:"",
    // city:"",
    address: "",
    email: ""
  });

  const [validationError, setValidationError] = useState<{
    phone_number: string | null;
    address: string | null;
    name: string | null;
    email: string | null
  }>({
    phone_number: null,
    address: null,
    name: null,
    email: null
  });

  useEffect(() => {
    const lead = localStorage.getItem("lead");

    if (!lead) {
      const timer = setTimeout(() => {
        setOpen(true);
      }, 2500); // 2.5 seconds

      return () => clearTimeout(timer);
    }
  }, []);

  const checkValidation = (key: string, value: string) => {
    let error: string | null = null;

    switch (key) {
      case "phone_number": {
        const phoneRegex = /^[6-9]\d{9}$/;

        if (!phoneRegex.test(value)) {
          error = "Invalid Indian phone number";
        }
        break;
      }

      case "name": {
        const usernameRegex = /^[A-Za-z][A-Za-z0-9_ ]{2,23}$/;

        if (value.length < 3 || value.length > 20) {
          error = "Username must be 3–25 characters";
        } else if (!usernameRegex.test(value)) {
          error =
            "Name must start with a letter and contain only letters, numbers, and _";
        }
        break;
      }

      case "address": {
        const cityRegex = /^[A-Za-z\s.\-', ]{2,50}$/;
        if (value.length < 2 || value.length > 500) {
          error = "Location must be 2–500 characters";
        } else if (!cityRegex.test(value)) {
          error = "Location can only contain letters, spaces, dots, hyphens";
        }
        break;
      }

      case "email": {
        const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;

        if (!value || value.trim() === "") {
          // optional field, no validation
          break;
        }

        if (value.length > 500) {
          error = "Email must be less than 500 characters";
        } else if (!emailRegex.test(value)) {
          error = "Please enter a valid email address";
        }

        break;
      }

      default:
        error = null;
    }

    setValidationError((prev) => ({
      ...prev,
      [key]: error,
    }));

    return error;
  };

  const router = useRouter();

  const validateForm = () => {
    const nameError = checkValidation("name", formData.name);
    const phoneError = checkValidation("phone_number", formData.phone_number);
    const addressError = checkValidation("city", formData.address);
    const emailError = checkValidation("email", formData.email);
    const hasError = nameError || phoneError || addressError || emailError;

    return !hasError;
  };

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();

    // Name validation
    if (!formData.name.trim()) {
      toast.error("Name is required");
      return;
    }

    const isValid = validateForm();

    if (!isValid) {
      toast.error("Please fix validation errors");
      return;
    }

    setLoading(true);

    try {
      const response = await apiCall<any>("/clientapi/leadsebmit", {
        method: "POST",
        body: {
          name: formData.name.trim(),
          phone_number: formData.phone_number.trim(),
          // state:formData.state.trim(),
          // city:formData.city.trim(),
          address: formData.address.trim(),
        },
      });

      if (response.error) {
        toast.error(response.error);
        return;
      }

      if (response.data?.success) {
        localStorage.setItem("lead", JSON.stringify(response.data.data));

        toast.success("Thank you for your Inquiry");

        setFormData({
          name: "",
          phone_number: "",
          // state:"",
          // city:"",
          address: "",
          email: ''
        });

        setOpen(false);

        // router.push("/thankingyou");
      } else {
        toast.error("Failed to submit lead");
      }
    } catch (error) {
      console.error(error);

      toast.error("Something went wrong. Please try again.");
    } finally {
      setLoading(false);
    }
  };

  return (
    <LeadFormDialog
      open={open}
      onOpenChange={setOpen}
      formData={formData}
      setFormData={setFormData}
      location={"home"}
      checkValidation={checkValidation}
      validationError={validationError}
      handleSubmit={handleSubmit}
      loading={loading}
    />
  );
}
