import { useEffect, useState } from "react"
import { useNavigate } from "react-router-dom"
import PhoneInput from "react-phone-input-2"
import { useTranslation } from "react-i18next"
import { Button } from "../../../ui-component/button/button.component"
import { Input } from "../../../ui-component/input/input.component"
import { ToggleButton } from "../../../ui-component/toggle-button/toggle-button.component"
import { Navigation } from "../../../ui-component/navigation/navigation.component"
import { Footer } from "../../../ui-component/footer/footer.component"
import { UploadCard } from "../../../ui-component/upload-card/upload-card.component.tsx"
import { PaymentMethodData } from "../payment-method-data/payment-method-data.component.tsx"
import styles from "./engineer-edit-profile.module.css"
import engineerImg from "../../../../public/images/project-request.png"
import { useEngineerProfile } from "../../../hooks/use-user.hook.ts"
import { EngineerProfileType } from "../../../types/user.type.ts"
import { useStacks } from "../../../context/stack.context.tsx"
import { DropdownItems } from "../../../ui-component/dropdown/dropdown.component.tsx"
import { countryList } from "../../user-sign-up/country.dictionary.ts"
import { Config } from "../../../utils/config.ts"

export function EngineerEditProfile() {
  // ---------------------------------------------------------------------------
  // variables
  // ---------------------------------------------------------------------------

  const { stacks } = useStacks()
  const navigate = useNavigate()
  const { t: translate } = useTranslation()
  const accountProfile = useEngineerProfile()
  const [mode, setMode] = useState<"main" | "description">("main")
  const [selectedItem, setSelectedItem] = useState<number>()
  const [profile, setProfile] = useState<EngineerProfileType>({
    id: "",
    name: "",
    email: "",
    phone: null,
    stack: {
      id: "",
      title: "",
      order: 0,
      photoUrl: "",
    },
    github: null,
    experience: null,
    paymentMethods: [],
    about: null,
    platformGoals: null,
    skills: [],
    profilePicture: null,
    country: null,
  })

  const [errors, setErrors] = useState({
    name: "",
    surname: "",
    email: "",
    phone: "",
    message: "",
  })

  // ---------------------------------------------------------------------------
  // effect
  // ---------------------------------------------------------------------------

  useEffect(() => {
    if (!accountProfile) return
    setProfile(accountProfile)
  }, [])

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

  function validateField(field: string, value: string) {
    let errorMsg = ""

    if (field === "name" || field === "surname") {
      if (!value) {
        errorMsg = `${
          field.charAt(0).toUpperCase() + field.slice(1)
        } is required.`
      }
    } else if (field === "email") {
      const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/
      if (!value) {
        errorMsg = "Email is required."
      } else if (!emailRegex.test(value)) {
        errorMsg = "Invalid email address."
      }
    } else if (field === "phone") {
      if (!value) {
        errorMsg = "Phone number is required."
      }
    } else if (field === "message") {
      if (!value) {
        errorMsg = "Message is required."
      }
    }

    setErrors((prevErrors) => ({ ...prevErrors, [field]: errorMsg }))
    return errorMsg === ""
  }

  // function validateForm() {
  // const isValidName = validateField("name", name)
  // const isValidSurname = validateField("surname", surname)
  // const isValidEmail = validateField("email", email)
  // const isValidPhone = validateField("phone", phone)
  // const isValidMessage = validateField("message", message)
  // return (
  //   isValidName &&
  //   isValidSurname &&
  //   isValidEmail &&
  //   isValidPhone &&
  //   isValidMessage
  // )
  // }

  async function handleSubmit() {
    if (!accountProfile) return
    const userData = {
      id: accountProfile.id,
      updated_at: Math.floor(Date.now() / 1000),
      name: profile.name,
      email: profile.email,
      phone: profile.phone,
      stack: profile.stack,
      github: profile.github,
      experience: profile.experience,
      paymentMethods: profile.paymentMethods,
      about: profile.about,
      platformGoals: null,
      skills: profile.skills,
      profilePicture: profile.profilePicture,
      country: profile.country,
    }

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

      console.log("====================================")
      console.log("response", response)
      console.log("====================================")

      if (!response.ok) {
        alert("Something went wrong!")
        return
      }

      const result: EngineerProfileType = await response.json()
      setProfile(result)
      navigate(-1)
    } catch (error) {
      alert("Network error. Please try again.")
    }
  }

  // ---------------------------------------------------------------------------
  if (!accountProfile) return null
  return (
    <>
      {/* --------------------------------------------------------------------------- */}
      {/* NAVIGATION  */}
      {/* --------------------------------------------------------------------------- */}

      <Navigation />
      <div className={styles.editProfileContainer}>
        <div className={styles.editProfileHeader}>
          <h1 className={styles.editProfileLabel}>
            {translate("navbar.editing-profile")}
          </h1>
          <div className={styles.editprofileToggleButton}>
            <ToggleButton
              labelOne="Main Infromation"
              labelTwo="Description"
              onClickLabelOne={() => {
                setMode("main")
              }}
              onClickLabelTwo={() => {
                setMode("description")
              }}
              activeLabel={mode === "main" ? "labelOne" : "labelTwo"}
            />
          </div>
        </div>
      </div>
      {mode === "main" && (
        <div className={styles.EditProfileItemContainer}>
          <UploadCard className={styles.photo} photo={engineerImg} />
          <div className={styles.editProfileInputsContainer}>
            {/* --------------------------------------------------------------------------- */}
            {/* NAME & COUNTRY  */}
            {/* --------------------------------------------------------------------------- */}

            <div className={styles.inputs}>
              <div className={styles.input}>
                <label className={styles.inputLables} htmlFor="name commpany">
                  Name
                </label>
                <Input
                  placeholder="Angelina Martinez"
                  value={profile.name}
                  onChange={(e) => {
                    setProfile((prev) => ({ ...prev, name: e.target.value }))
                    validateField("name company", e.target.value)
                  }}
                />
                {errors.name && <p className={styles.error}>{errors.name}</p>}
              </div>
              <div className={styles.input}>
                <label className={styles.inputLables} htmlFor="url">
                  Country
                </label>

                <DropdownItems
                  key={countryList.length}
                  menuClassName={styles.menu}
                  checkboxes={false}
                  items={countryList}
                  mode="secondary"
                  itemRender={(country) => (
                    <span key={country.length} className={styles.menuItem}>
                      {country}
                    </span>
                  )}
                  checked={(country) =>
                    !!profile.country && profile.country === country
                  }
                  onChange={(value) =>
                    setProfile((prev) => ({
                      ...prev,
                      country: value as string,
                    }))
                  }
                  placeholder={"Country"}
                />
                {errors.surname && (
                  <p className={styles.error}>{errors.surname}</p>
                )}
              </div>
            </div>

            {/* --------------------------------------------------------------------------- */}
            {/* EMAIL & LINK  */}
            {/* --------------------------------------------------------------------------- */}

            <div className={styles.inputs}>
              <div className={styles.input}>
                <label className={styles.inputLables} htmlFor="email">
                  Email
                </label>
                <Input
                  placeholder="Andel_Matz@gmail.com"
                  value={profile.email}
                  onChange={(e) => {
                    setProfile((prev) => ({ ...prev, email: e.target.value }))
                    validateField("email", e.target.value)
                  }}
                />
                {errors.email && <p className={styles.error}>{errors.email}</p>}
              </div>
              <div className={styles.input}>
                <label className={styles.inputLables} htmlFor="phone">
                  Github
                </label>
                <Input
                  placeholder="Share the link to the resource"
                  value={profile.github ? profile.github : ""}
                  onChange={(e) => {
                    setProfile((prev) => ({ ...prev, github: e.target.value }))
                    validateField("post", e.target.value)
                  }}
                />
                {errors.surname && (
                  <p className={styles.error}>{errors.surname}</p>
                )}
                {errors.phone && <p className={styles.error}>{errors.phone}</p>}
              </div>
            </div>

            {/* --------------------------------------------------------------------------- */}
            {/* PHONE  */}
            {/* --------------------------------------------------------------------------- */}

            <div className={styles.inputs}>
              <div className={styles.input}>
                <label className={styles.inputLables} htmlFor="contact">
                  Phone
                </label>
                <PhoneInput
                  inputStyle={{
                    height: "4.8rem",
                    backgroundColor: "#f6f2fa",
                    width: "100%",
                    borderRadius: "1.5rem",
                    border: "1px solid none",
                  }}
                  country={"jp"}
                  value={profile.phone}
                  onChange={(value) => {
                    setProfile((prev) => ({ ...prev, phone: value }))
                    validateField("phone", value)
                  }}
                />
                {errors.name && <p className={styles.error}>{errors.name}</p>}
              </div>
            </div>

            {/* --------------------------------------------------------------------------- */}
            {/* STACK && EXPERIENCE  */}
            {/* --------------------------------------------------------------------------- */}

            <div className={styles.inputs} style={{ marginTop: "2rem" }}>
              <div className={styles.input}>
                <label className={styles.inputLables} htmlFor="post">
                  Stack
                </label>

                <DropdownItems
                  key={stacks.length}
                  menuClassName={styles.menu}
                  checkboxes={false}
                  items={stacks}
                  mode="secondary"
                  itemRender={(stack) => (
                    <span key={stack.id} className={styles.menuItem}>
                      {stack.title}
                    </span>
                  )}
                  checked={(stack) => profile.stack.id === stack.id}
                  onChange={(value) =>
                    setProfile((prev) => ({ ...prev, stack: value }))
                  }
                  placeholder={"Stack"}
                />
              </div>
              <div className={styles.input}>
                <label className={styles.inputLables} htmlFor="contact">
                  Experience years
                </label>
                <Input
                  placeholder="Write down your work experience"
                  value={profile.experience ? profile.experience : ""}
                  onChange={(e) => {
                    setProfile((prev) => ({
                      ...prev,
                      experience: e.target.value,
                    }))
                    validateField("contact-person", e.target.value)
                  }}
                />
                {errors.name && <p className={styles.error}>{errors.name}</p>}
              </div>
              <div className={styles.input}>
                {PaymentMethodData.map((payment, index) => (
                  <div key={index}>
                    <h3 className={styles.paymentMethodLabel}>
                      {payment.title}
                    </h3>
                    <div className={styles.paymentMethodTypes}>
                      {payment.type.map((type, index) => (
                        <span
                          key={index}
                          className={`${styles.paymentMethodDataStyles} ${selectedItem === index && styles.active}`}
                          onClick={() => setSelectedItem(index)}
                        >
                          {type}
                        </span>
                      ))}
                    </div>
                  </div>
                ))}
              </div>
            </div>

            {/* --------------------------------------------------------------------------- */}
            {/* FOOTER  */}
            {/* --------------------------------------------------------------------------- */}

            <div className={styles.editprofileButtons}>
              <Button
                mode="outline"
                className={styles.sendMessageBtn}
                onClick={() => navigate(-1)}
              >
                {translate("button.cancel")}
              </Button>
              <Button className={styles.sendMessageBtn} onClick={handleSubmit}>
                {translate("button.save-changes")}
              </Button>
            </div>
          </div>
        </div>
      )}

      {/* --------------------------------------------------------------------------- */}
      {/* DESC  */}
      {/* --------------------------------------------------------------------------- */}

      {mode === "description" && (
        <>
          <div className={styles.editProfileDescriptionPage}>
            <div className={styles.editProfileDescription}>
              <div className={styles.descriptionInput}>
                <label className={styles.descriptionInputLables} htmlFor="url">
                  About
                </label>
                <Input
                  placeholder="Write about yourself so that companies know more about you"
                  value={profile.about ? profile.about : ""}
                  onChange={(e) => {
                    setProfile((prev) => ({
                      ...prev,
                      about: e.target.value,
                    }))
                    validateField("url", e.target.value)
                  }}
                />
                {errors.surname && (
                  <p className={styles.error}>{errors.surname}</p>
                )}
              </div>
              <div className={styles.descriptionInput}>
                <label className={styles.descriptionInputLables} htmlFor="url">
                  Goals on platform
                </label>
                <Input
                  placeholder="Tell us about your goals on the platform"
                  value={profile.platformGoals ? profile.platformGoals : ""}
                  onChange={(e) => {
                    setProfile((prev) => ({
                      ...prev,
                      platformGoals: e.target.value,
                    }))
                    validateField("url", e.target.value)
                  }}
                />
                {errors.surname && (
                  <p className={styles.error}>{errors.surname}</p>
                )}
              </div>
              <div className={styles.descriptionButtons}>
                <Button
                  mode="outline"
                  className={styles.descriptionBtn}
                  onClick={() => navigate(-1)}
                >
                  {translate("button.cancel")}
                </Button>
                <Button
                  className={styles.descriptionBtn}
                  onClick={handleSubmit}
                >
                  {translate("button.save-changes")}
                </Button>
              </div>
            </div>
          </div>
        </>
      )}
      <Footer />
    </>
  )
}
i wanna fix payment method when i choose it, i send them to server