import { useState } from "react"
import { useAuth } from "../../ui-component/auth-context/auth-context"
import { Button } from "../../ui-component/button/button.component"
import { Input } from "../../ui-component/input/input.component"
import { useModal } from "../../ui-component/modal"
import { Config } from "../../utils/config"
import { UserSignUpComponent } from "../user-sign-up/user-sign-up.component"
import styles from "./user-sign-in.styles.module.css"
import { CurrentUserType } from "../../types/user.type"

type FormData = {
  email: string
  password: string
}

type Errors = Partial<Record<keyof FormData, string>>

export function UserSignInComponent() {
  // ---------------------------------------------------------------------------
  // states
  // ---------------------------------------------------------------------------

  const modal = useModal()
  const { login } = useAuth()

  const [formData, setFormData] = useState<FormData>({
    email: "",
    password: "",
  })
  const [errors, setErrors] = useState<Errors>({})
  const [showPassword, setShowPassword] = useState(false)

  // ---------------------------------------------------------------------------
  // functions
  // ---------------------------------------------------------------------------

  function openSignUp() {
    modal.open({
      component: <UserSignUpComponent />,
      width: "80rem",
      closeOnEsc: true,
      closeOnOutsideClick: true,
      modalClassName: styles.modal,
      closeIconClassName: styles.xModal,
    })
  }

  const handleSignIn = async () => {
    // if (!formData.agreeToTerms) {
    //   alert("You must agree to the terms and conditions!")
    //   return
    // }

    if (validate()) {
      const userData = {
        email: formData.email,
        password: formData.password,
      }

      try {
        const response = await fetch(`${Config.url}/api/auth/login`, {
          method: "POST",
          headers: {
            "Content-Type": "application/json",
          },
          body: JSON.stringify(userData),
          credentials: "include",
        })

        if (response.ok) {
          const result: CurrentUserType = await response.json()
          login(result)
          const error = await response.json()
          alert(error.message || "Something went wrong!")
          modal.close()
        }
      } catch (error) {
        alert("Network error. Please try again.")
      }
    }
  }

  const validate = () => {
    let newErrors: Errors = {}

    if (!/\S+@\S+.\S+/.test(formData.email)) {
      newErrors.email = "Email address is invalid"
    } else if (!formData.email) {
      newErrors.email = "Email is required"
    } else if (formData.email.length > 100) {
      newErrors.email = "Email should be less than 100 characters"
    } else if (!formData.password) {
      newErrors.password = "Password is required"
    } else if (formData.password.length < 6) {
      newErrors.password = "Password must be at least 6 characters"
    }

    setErrors(newErrors)
    return Object.keys(newErrors).length === 0
  }

  const handleValueChange = (
    field: keyof FormData,
    value: string | boolean,
  ) => {
    setFormData({ ...formData, [field]: value })
  }

  // ---------------------------------------------------------------------------
  return (
    <>
      <div className={styles.container}>
        <div className={styles.signInContainer}>
          <h1>Sign In</h1>
          <div className={styles.input}>
            <Input
              mode="primary"
              placeholder="Mail"
              autofocus={true}
              value={formData.email}
              onValueChange={(value) => handleValueChange("email", value)}
            />

            <span className={styles.error}>{errors.email}</span>

            <Input
              mode="primary"
              type={showPassword ? "text" : "password"}
              placeholder="Password"
              iconRight={
                showPassword ? "fa-light fa-eye" : "fa-light fa-eye-slash"
              }
              onIconClick={() => setShowPassword(!showPassword)}
              value={formData.password}
              onValueChange={(value) => handleValueChange("password", value)}
            />
            <span className={styles.error}>{errors.password}</span>

            <Button
              className={styles.nextButton}
              disabled={
                formData.email.length === 0 || formData.password.length === 0
              }
              onClick={() => {
                handleSignIn()
              }}
            >
              Continue
            </Button>
            <p>
              If you haven't registered yet,
              <br /> go through a simple registration.{" "}
              <span className={styles.registerBtn} onClick={openSignUp}>
                Registration
              </span>
            </p>
          </div>
        </div>
        <div className={styles.imageContainer}></div>
      </div>
    </>
  )
}
when I try to login first it goes to catch and show  alert("Network error. Please try again.") then When I click ok button then it goes to try. Why ?