/* eslint-disable no-empty */
/* eslint-disable react-hooks/exhaustive-deps */
/* eslint-disable @typescript-eslint/no-explicit-any */

import countriesData from "../../../../../data/countries.json";

import styles from "../steps.module.scss";

import { Input } from "@/components/ui/input";

import { useEffect, useRef, useState } from "react";

const getFlagEmoji = (code: string) =>
  code.toUpperCase().replace(/./g, (char) =>
    String.fromCodePoint(
      127397 + char.charCodeAt(0)
    )
  );

const getCountryByName = (
  name: string
) =>
  countriesData.find(
    (c: any) => c.name === name
  );

const getCountryByCode = (
  code: string
) =>
  countriesData.find(
    (c: any) => c.code === code
  );

const formatPhone = (
  value: string,
  prefix: string
) => {
  const raw = value
    .replace(prefix, "")
    .replace(/\D/g, "");

  return (
    prefix +
    raw
      .replace(/(.{3})/g, "$1 ")
      .trim()
  );
};

const PersonalInfo = ({
  handleNextClick,
  value,
  setData,
}: any) => {
  const {
    name,
    country,
    username,
    phone,
    gender,
  } = value;

  const [formFilled, setFormFilled] =
    useState(false);

  const [dialCode, setDialCode] =
    useState("");

  const [loadingCountry, setLoadingCountry] =
    useState(true);

  const phoneRef =
    useRef<HTMLInputElement>(null);

  useEffect(() => {
    setFormFilled(
      Boolean(
        name &&
          country &&
          username &&
          phone &&
          gender
      )
    );
  }, [
    name,
    country,
    username,
    phone,
    gender,
  ]);

  const resolveDialCode = async (
    isoCode: string
  ) => {
    try {
      const res = await fetch(
        `https://restcountries.com/v3.1/alpha/${isoCode}`
      );

      const data = await res.json();

      const root =
        data?.[0]?.idd?.root || "";

      const suffix =
        data?.[0]?.idd?.suffixes?.[0] ||
        "";

      const full = `${root}${suffix}`;

      setDialCode(full);

      setData("phone", full);
    } catch {}
  };

  useEffect(() => {
    const detectCountry =
      async () => {
        try {
          const res =
            await fetch(
              "https://ipapi.co/json/"
            );

          const data =
            await res.json();

          const detected =
            getCountryByCode(
              data.country_code
            );

          if (detected) {
            setData(
              "country",
              detected.name
            );

            await resolveDialCode(
              detected.code
            );
          }
        } finally {
          setLoadingCountry(
            false
          );
        }
      };

    if (!country)
      detectCountry();
    else
      setLoadingCountry(false);
  }, [country]);

  const handleCountryChange =
    async (name: string) => {
      const selected =
        getCountryByName(name);

      if (!selected) return;

      setData("country", name);

      await resolveDialCode(
        selected.code
      );

      phoneRef.current?.focus();
    };

  const handlePhoneChange = (
    val: string
  ) => {
    if (
      !val.startsWith(dialCode)
    ) {
      setData(
        "phone",
        dialCode
      );

      return;
    }

    setData(
      "phone",
      formatPhone(
        val,
        dialCode
      )
    );
  };

  if (loadingCountry) {
    return (
      <div className={styles.steps}>
        <div
          className={
            styles.skeleton
          }
        />
      </div>
    );
  }

  return (
    <div className={styles.steps}>
      <h2>
        Personal Details
      </h2>

      <p>
        Please tell us a bit about yourself.
      </p>

      <div
        className={
          styles.steps__row
        }
      >
        <div>
          <label>
            Full Name
          </label>

          <Input
            value={name}
            placeholder="John Doe"
            onChange={(e) =>
              setData(
                "name",
                e.target.value
              )
            }
          />
        </div>

        <div>
          <label>
            Username
          </label>

          <Input
            value={username}
            placeholder="johndoe"
            onChange={(e) =>
              setData(
                "username",
                e.target.value
              )
            }
          />
        </div>
      </div>

      <div
        className={
          styles.steps__row
        }
      >
        <div>
          <label>
            Country
          </label>

          <select
            value={country}
            className={
              styles.custom_input
            }
            onChange={(e) =>
              handleCountryChange(
                e.target.value
              )
            }
          >
            <option value="">
              Select Country
            </option>

            {countriesData.map(
              (c: any) => (
                <option
                  key={c.code}
                  value={c.name}
                >
                  {getFlagEmoji(
                    c.code
                  )}{" "}
                  {c.name}
                </option>
              )
            )}
          </select>
        </div>

        <div>
          <label>
            Phone
          </label>

          <Input
            ref={phoneRef}
            value={phone}
            placeholder={
              dialCode
            }
            onChange={(e) =>
              handlePhoneChange(
                e.target.value
              )
            }
          />
        </div>
      </div>

      <div>
        <label>
          Gender
        </label>

        <select
          value={gender}
          className={
            styles.custom_input
          }
          onChange={(e) =>
            setData(
              "gender",
              e.target.value
            )
          }
        >
          <option value="">
            Select Gender
          </option>

          <option value="male">
            Male
          </option>

          <option value="female">
            Female
          </option>
        </select>
      </div>

      <div
        className={
          styles.steps__buttons
        }
      >
        <div
          onClick={
            formFilled
              ? handleNextClick
              : undefined
          }
          className={
            formFilled
              ? styles[
                  "steps__buttons__button--next"
                ]
              : styles[
                  "steps__buttons__button--next--disabled"
                ]
          }
        >
          Next Step
        </div>
      </div>
    </div>
  );
};

export default PersonalInfo;