"use client";

import { useState } from "react";
import Input from "../../ui/CustomInput";
import Button from "../../ui/Button";

import { FiUser, FiMail, FiLock, FiEye, FiEyeOff } from "react-icons/fi";
import { IoPerson } from "react-icons/io5";
import { useModal } from "../../../lib/modal-system/ModalContext";
import { useAppForm } from "../../../hooks/useAppForm";
import {
  signupSchema,
  SignupSchema,
} from "../../../hooks/features/auth/signup/schema";
import useRegister from "../../../hooks/features/auth/signup/useRegister";
import { AxiosError } from "axios";
import { formatStringWithUppercase } from "../../../utils/helper";
import CustomPhoneInput from "../../ui/CustomPhoneInput";
import Link from "next/link";
import CustomLink from "../../ui/CustomLink";

export default function SignupForm() {
  const [showPassword, setShowPassword] = useState(false);
  const [showConfirmPassword, setShowConfirmPassword] = useState(false);

  const { openModal, closeModal } = useModal();

  const { handleSignup, loading } = useRegister();
  const { register, handleSubmit, errors, reset, setError, control } =
    useAppForm<SignupSchema>({
      defaultValues: {
        firstName: "",
        lastName: "",
        email: "",
        password: "",
        mobileNumber: {
          dialCode: "",
          number: "",
        },
        confirmPassword: "",
      },
      schema: signupSchema,
      onSubmit: async (data) => {
        try {
          await handleSignup(data);

          reset();
          openModal("CHECK_EMAIL_FOR_VERIFICATION", {
            email: data.email,
          });
        } catch (error) {
          const axiosError = error as AxiosError<{
            message?: string;
            errors?: Record<string, string[]>;
          }>;

          const fieldErrors = axiosError?.response?.data?.errors;

          if (fieldErrors) {
            Object.entries(fieldErrors).forEach(([field, messages]) => {
              if (field.startsWith("mobileNumber")) {
                setError("mobileNumber.number", {
                  type: "server",
                  message: formatStringWithUppercase(messages[0]),
                });
              } else {
                setError(field as keyof SignupSchema, {
                  type: "server",
                  message: formatStringWithUppercase(messages[0]),
                });
              }
            });
          }
        }
      },
    });

  return (
    <>
      {/* <div className="mx-auto mb-5 flex h-16 w-16 items-center justify-center rounded-full border-2 border-link-1/20">
        <IoPerson size={28} className="text-link-1" />
      </div> */}

      <h2 className="font-heading text-xl text-center font-semibold text-heading">
        Create your account
      </h2>

      <p className="mt-2 text-center font-body text-base text-text">
        Sign up and unlock instant access to AI image detection.
      </p>

      {/* First & Last Name */}
      <div className="mt-8 grid gap-3 md:grid-cols-2">
        <Input
          label="First Name"
          required
          icon={<FiUser />}
          register={register("firstName")}
          error={errors.firstName?.message}
          placeholder="Enter Your First Name"
        />
        <Input
          label="Last Name"
          required
          icon={<FiUser />}
          register={register("lastName")}
          error={errors.lastName?.message}
          placeholder="Enter Your Last Name"
        />
      </div>
      <div className="mt-3">
        <Input
          label="Email"
          required
          icon={<FiMail />}
          register={register("email")}
          error={errors.email?.message}
          placeholder="Enter Your Email"
        />
      </div>
      <div className="mt-3">
        <CustomPhoneInput
          label="Phone Number"
          required
          control={control}
          error={errors.mobileNumber?.number?.message}
          name="mobileNumber"
          placeholder="Enter Your Phone Number"
        />
      </div>

      {/* Password */}
      <div className="mt-3">
        <Input
          label="Password"
          required
          icon={<FiLock />}
          type={showPassword ? "text" : "password"}
          placeholder="Enter Your Password"
          register={register("password")}
          error={errors.password?.message}
          rightIcon={
            <button
              type="button"
              onClick={() => setShowPassword(!showPassword)}
              className="text-link-1 cursor-pointer"
            >
              {showPassword ? <FiEyeOff size={18} /> : <FiEye size={18} />}
            </button>
          }
        />
      </div>

      {/* Confirm Password */}
      <div className="mt-3">
        <Input
          label="Confirm Password"
          required
          icon={<FiLock />}
          type={showConfirmPassword ? "text" : "password"}
          placeholder="Confirm Your Password"
          register={register("confirmPassword")}
          error={errors.confirmPassword?.message}
          rightIcon={
            <button
              type="button"
              onClick={() => setShowConfirmPassword(!showConfirmPassword)}
              className="text-link-1 cursor-pointer"
            >
              {showConfirmPassword ? (
                <FiEyeOff size={18} />
              ) : (
                <FiEye size={18} />
              )}
            </button>
          }
        />
      </div>

      <Button loading={loading} className="mt-8 w-full" onClick={handleSubmit}>
        Sign Up
      </Button>

      <p className="mt-5 text-center text-sm text-text">
        By signing up, you agree to our{" "}
        <CustomLink
          href="/terms-and-conditions"
          target="_blank"
          className="font-medium text-link-1 cursor-pointer"
        >
          Terms of Service
        </CustomLink>{" "}
        and{" "}
        <CustomLink
          href="/privacy-policy"
          target="_blank"
          className="font-medium text-link-1 cursor-pointer"
        >
          Privacy Policy
        </CustomLink>
      </p>

      <p className="mt-5 text-center text-sm text-text">
        Already have an account?
        <button
          type="button"
          onClick={() => openModal("LOGIN", {})}
          className="ml-1 font-medium text-link-1 cursor-pointer"
        >
          Sign In
        </button>
      </p>
    </>
  );
}
