import { useRouter } from "next/router";
import { ChangeEvent, FormEvent, useEffect, useReducer, useState } from "react";
import Select from "react-select";
import Swal from "sweetalert2";
import UseFullScreenLoader from "../../../hooks/UseFullScreenLoader";
import {
  useGetCities,
  useGetCountries,
  useGetJobPostSkills,
  useGetQualifications,
  useGetStates,
} from "../../../utils/hooks";
import { useDeleteCandidate } from "../../../utils/hooks/useDeleteCandidate";
import { useUpdateCandidateProfile } from "../../../utils/hooks/useUpdateCandidateProfile";
import { useGetFileType } from "../../../hooks/useGetFileType";

const initialState: CandidateProfileDetails = {
  firstName: "",
  lastName: "",
  address: "",
  birthdate: "",
  city: "",
  country: "",
  gender: "",
  phone: "",
  pronouns: "",
  state: "",
  careerObjective: "",
  keyAchievement: "",
  summary: "",
  zipcode: "",
  candidateImage: "",
  qualificationId: [],
  skillIds: [],
  loading: false,
  applicationsCount: 0,
  jobAlerts: 0,
  messageCounts: 0,
  shortlistCount: 0,
  applications: [],
  notifications: [],
  profilePictureUrl: "",
  recentJobsApplied: [],
  userId: 0,
};

const formReducer = (state: any, action: any) => {
  switch (action.type) {
    case "SET_FORM_DATA":
      return { ...state, ...action.payload };
    case "UPDATE_FIELD":
      return { ...state, [action.field]: action.value };
    case "UPDATE_SKILLS":
      return { ...state, skillIds: action.value };
    case "UPDATE_LOADING":
      return { ...state, loading: action.value };
    case "UPDATE_IMAGE":
      return { ...state, candidateImage: action.value };
    default:
      return state;
  }
};

const FormInfoBox = ({
  candidateProfileDetails,
}: {
  candidateProfileDetails: CandidateProfileDetails;
}) => {
  const [state, dispatch] = useReducer(formReducer, initialState);
  const [getSkills, setSkills] = useState<any>([]);
  const [getQalifications, setQalifications] = useState<quaificationSelect[]>(
    []
  );
  const [countries, setCountries] = useState<CountryData[]>();
  const [selectedCountry, setSelectedCountry] = useState<number | null>(null);
  const [states, setStates] = useState<StatesData[]>();
  const [selectedState, setSelectedState] = useState<number | null>(null);
  const [cities, setCities] = useState<CitiesData[]>();
  const router = useRouter();

  useEffect(() => {
    if (candidateProfileDetails) {
      dispatch({
        type: "SET_FORM_DATA",
        payload: {
          firstName: candidateProfileDetails.firstName || "",
          lastName: candidateProfileDetails.lastName || "",
          address: candidateProfileDetails.address || "",
          birthdate: candidateProfileDetails.birthdate || "",
          city: candidateProfileDetails.city || "",
          country: candidateProfileDetails.country || "",
          gender: candidateProfileDetails.gender || "",
          phone: candidateProfileDetails.phone || "",
          pronouns: candidateProfileDetails.pronouns || "",
          state: candidateProfileDetails.state || "",
          summary: candidateProfileDetails.summary || "",
          zipcode: candidateProfileDetails.zipcode || "",
          profilePictureUrl: candidateProfileDetails.profilePictureUrl || "",
          skillIds:
            candidateProfileDetails.skills?.map((skill: any) => skill?.id) ||
            [],
          qualificationId: candidateProfileDetails.qualificationId || [],
        },
      });
    }
  }, [candidateProfileDetails]);

  const handleInputChange = (
    e:
      | ChangeEvent<HTMLInputElement>
      | ChangeEvent<HTMLTextAreaElement>
      | ChangeEvent<HTMLSelectElement>
  ) => {
    const { name, value } = e.target;
    dispatch({
      type: "UPDATE_FIELD",
      field: name,
      value: value,
    });
  };

  const handleFileChange = async (e: any) => {
    const { name, files } = e.target;
    // console.log(e.target.files[0]?.name);
    const fileType = await useGetFileType(files[0]);
    if (fileType !== "image") {
      Swal.fire({
        icon: "error",
        title: "Oops...",
        text: "Only image files are allowed",
      }).then(() => {
        e.target.value = "";
        return;
      });
    }
    dispatch({
      type: "UPDATE_IMAGE",
      field: name,
      value: files[0],
    });
  };

  const handleSelectChange = (selectedOptions: any, actionMeta: any) => {
    if (actionMeta.name === "skillIds") {
      const selectedValues = selectedOptions.map((option: any) => option.value);
      dispatch({
        type: "UPDATE_SKILLS",
        value: selectedValues,
      });
    } else {
      dispatch({
        type: "UPDATE_FIELD",
        field: actionMeta.name,
        value: `${selectedOptions.value}`,
      });
    }
  };

  const handleCountryChange = (e: any) => {
    setSelectedCountry(e.target.value);
    setStates([]);
    setCities([]);
    const { name, value } = e.target;
    dispatch({
      type: "UPDATE_FIELD",
      field: name,
      value: value,
    });
  };
  const handleStateChange = (e: any) => {
    setSelectedState(e.target.value);
    const { name, value } = e.target;
    dispatch({
      type: "UPDATE_FIELD",
      field: name,
      value: value,
    });
  };
  const handleCityChange = (e: any) => {
    const { name, value } = e.target;
    dispatch({
      type: "UPDATE_FIELD",
      field: name,
      value: value,
    });
  };

  useEffect(() => {
    const getStates = async (id: number) => {
      if (selectedCountry) {
        try {
          const { resp, status } = (await useGetStates(id)) as Response;
          if (status === 200) {
            setStates(resp.data);
          }
        } catch (error) {
          console.error("Error fetching states:", error);
        }
      }
    };
    getStates(selectedCountry!);
  }, [selectedCountry]);

  useEffect(() => {
    const getCities = async (id: number) => {
      if (selectedCountry) {
        try {
          const { resp, status } = (await useGetCities(id)) as Response;
          if (status === 200) {
            setCities(resp.data);
          }
        } catch (error) {
          console.error("Error fetching states:", error);
        }
      }
    };
    getCities(selectedState!);
  }, [selectedState]);

  useEffect(() => {
    if (state.country) {
      setSelectedCountry(state.country);
    }
  }, [state.country]);
  useEffect(() => {
    if (state.country) {
      setSelectedState(state.state);
    }
  }, [state.state]);

  useEffect(() => {
    (async function () {
      // get the skills
      const skillsResp = (await useGetJobPostSkills()) as SkillResponse;
      const newSkills = skillsResp.data.map((skill) => ({
        value: skill.id,
        label: skill.name,
      }));
      setSkills(newSkills);

      // get the qualifications
      const qualificationsResp =
        (await useGetQualifications()) as SkillResponse;
      const newQualifications = qualificationsResp.data.map(
        (qualification) => ({
          value: qualification.id,
          label: qualification.name,
        })
      );
      setQalifications(newQualifications);
    })();
    const getCountries = async () => {
      try {
        const { resp, status } = (await useGetCountries()) as Response;
        if (status === 200) {
          setCountries(resp.data);
        }
      } catch (error) {
        console.error("Error fetching countries:", error);
      }
    };
    getCountries();
  }, []);

  const handleProfileUpdate = async (e: FormEvent<HTMLFormElement>) => {
    e.preventDefault();
    // set Loading to true
    dispatch({
      type: "UPDATE_LOADING",
      value: true,
    });

    try {
      // Assuming `useUpdateCandidateProfile` is a function that takes the profile data and updates it
      const { resp, status } = (await useUpdateCandidateProfile(
        state
      )) as Response;
      if (status === 200) {
        dispatch({
          type: "UPDATE_LOADING",
          value: false,
        });
        const ok = await Swal.fire({
          title: "Success!",
          text: "Updated Successfully!",
          icon: "success",
        });
        if (ok) {
          router.reload();
        }
      }
    } catch (error) {
      dispatch({
        type: "UPDATE_LOADING",
        value: false,
      });
      await Swal.fire({
        title: "Failed!",
        text: "Something went wrong!",
        icon: "error",
      });
      console.error("Error updating data", error);
    }
  };

  const handleDelete = async () => {
    const res = await Swal.fire({
      title: "Are you sure?",
      text: "You won't be able to revert this!",
      icon: "warning",
      showCancelButton: true,
      confirmButtonColor: "#3085d6",
      cancelButtonColor: "#d33",
      confirmButtonText: "Yes, delete it!",
    });
    if (res.isConfirmed) {
      dispatch({
        type: "UPDATE_LOADING",
        value: true,
      });
      const { resp, status } = (await useDeleteCandidate()) as Response;
      dispatch({
        type: "UPDATE_LOADING",
        value: false,
      });
      if (resp.success) {
        const ok = await Swal.fire({
          title: status == 200 ? "Success" : "Failed",
          text: resp.message,
          icon: status == 200 ? "success" : "error",
          confirmButtonColor: "#3085d6",
          cancelButtonColor: "#d33",
          confirmButtonText: "Ok",
        });
        if (ok.isConfirmed) {
          router.push("/logout");
        }
      } else {
        await Swal.fire({
          title: "Failed!",
          text: "Something went wrong!",
          icon: "error",
        });
      }
    }
  };

  return (
    <>
      {state.loading && <UseFullScreenLoader text={"Loading..."} />}
      <form className="default-form" onSubmit={handleProfileUpdate}>
        <div className="uploading-outer">
          {state.profilePictureUrl ? (
            <img
              src={state.profilePictureUrl}
              alt={`Profile Picture of ${state.firstName}`}
              className="profile-avatar"
              onError={(e) => {
                e.currentTarget.src = "/images/human_capital_logo.png";
                e.currentTarget.onerror = null;
              }}
            />
          ) : (
            <img
              src={"/images/human_capital_logo.png"}
              alt={`Profile Avatar`}
              className="profile-avatar"
            />
          )}
          <div className="uploadButton">
            <input
              className="uploadButton-input"
              type="file"
              name="candidateImage"
              accept="image/jpeg, image/png, image/gif, image/jpg"
              id="upload"
              onChange={handleFileChange}
            />
            <label
              className="uploadButton-button ripple-effect"
              htmlFor="upload"
            >
              {/* {logoImg ? logoImg.name : "Upload Photo"} */}
            </label>
            <span className="uploadButton-file-name"></span>
          </div>
          <div className="text">
            <p>
              Max file size is 2MB, Minimum dimension: 330x300 And Suitable
              files are .jpg & .png
            </p>
            <p>{state.candidateImage?.name}</p>
          </div>
        </div>
        <div className="row">
          <div className="form-group col-lg-6 col-md-12">
            <label>First Name</label>
            <input
              type="text"
              name="firstName"
              placeholder="First Name"
              value={state.firstName}
              onChange={handleInputChange}
            />
          </div>
          <div className="form-group col-lg-6 col-md-12">
            <label>Last Name</label>
            <input
              type="text"
              name="lastName"
              placeholder="Last Name"
              value={state.lastName}
              onChange={handleInputChange}
            />
          </div>
          <div className="form-group col-lg-6 col-md-12">
            <label>Phone</label>
            <input
              type="text"
              name="phone"
              placeholder="0 123 456 789"
              value={state.phone}
              onChange={handleInputChange}
            />
          </div>
          <div className="form-group col-lg-6 col-md-12">
            <label>Pronoun</label>
            {/* <input
                            type="text"
                            name="pronouns"
                            placeholder="Pronoun"
                            value={state.pronouns}
                            onChange={handleInputChange}
                        /> */}
            <select
              className="chosen-single form-select"
              name="pronouns"
              value={state.pronouns}
              onChange={handleInputChange}
            >
              <option disabled selected hidden>
                Please Select Gender
              </option>
              <option value="He/Him">He/Him</option>
              <option value="She/Her">She/Her</option>
              <option value="They/Them">They/Them</option>
            </select>
          </div>
          <div className="form-group col-lg-6 col-md-12">
            <label>Birth Date</label>
            <input
              type="date"
              name="birthdate"
              value={state.birthdate}
              onChange={handleInputChange}
            />
          </div>
          <div className="form-group col-lg-6 col-md-12">
            <label>Address</label>
            <input
              type="text"
              name="address"
              placeholder="Address"
              value={state.address}
              onChange={handleInputChange}
            />
          </div>
          <div className="form-group col-lg-6 col-md-12">
            <label>Country</label>
            <select
              name="country"
              onChange={handleCountryChange}
              value={state.country}
            >
              <option disabled selected hidden>
                Choose a Country
              </option>
              {countries?.map((country) => (
                <option value={country.id}>{country?.name}</option>
              ))}
            </select>
          </div>
          <div className="form-group col-lg-6 col-md-12">
            <label>State</label>
            <select
              name="state"
              onChange={handleStateChange}
              value={state.state}
            >
              <option value="" selected>
                Choose a State
              </option>
              {states?.map((state) => (
                <option value={state.id}>{state?.name}</option>
              ))}
            </select>
          </div>
          <div className="form-group col-lg-6 col-md-12">
            <label>City</label>
            <select name="city" onChange={handleCityChange} value={state.city}>
              <option value="" selected>
                Choose a City
              </option>
              {cities?.map((city) => (
                <option value={city.id}>{city?.name}</option>
              ))}
            </select>
          </div>
          <div className="form-group col-lg-6 col-md-12">
            <label>Zip Code</label>
            <input
              type="text"
              name="zipcode"
              placeholder="Zip/Postal Code"
              value={state.zipcode}
              onChange={handleInputChange}
            />
          </div>
          <div className="form-group col-lg-6 col-md-12">
            <label>Gender</label>
            <select
              className="chosen-single form-select"
              name="gender"
              value={state.gender}
              onChange={handleInputChange}
            >
              <option disabled selected hidden>
                Please Select Gender
              </option>
              <option value="Male">Male</option>
              <option value="Female">Female</option>
              <option value="Non-Binary">Non-Binary</option>
              <option value="Other">Others</option>
            </select>
          </div>
          <div className="form-group col-lg-6 col-md-12">
            <label>Skills</label>
            <Select
              isMulti
              name="skillIds"
              options={getSkills}
              value={getSkills.filter((option: any) =>
                state.skillIds.includes(option.value)
              )}
              onChange={handleSelectChange}
              className="basic-multi-select"
              classNamePrefix="select"
            />
          </div>
          {/* <div className="form-group col-lg-6 col-md-12">
                        <label>Qualification</label>
                        <select 
                            name="qualificationId" 
                            className="form-control" 
                            value={state.qualificationId}
                            onChange={handleInputChange}
                        >
                            {
                                getQalifications.map(qualification => (
                                    <option key={qualification.value} value={qualification.value}>{qualification.label}</option>
                                ))
                            }
                        </select>
                    </div> */}
          <div className="form-group col-lg-12 col-md-12">
            <label>Summary</label>
            <textarea
              placeholder="Brief description of candidate's profile"
              name="summary"
              value={state.summary}
              onChange={handleInputChange}
            />
          </div>
          <div className="form-group items-center justify-content-between d-flex">
            <button
              type="button"
              className="btn btn-danger theme-btn"
              style={{ minHeight: "45px" }}
              onClick={handleDelete}
            >
              Delete Profile
            </button>
            <button type="submit" className="theme-btn btn-style-one">
              Save
            </button>
          </div>
        </div>
      </form>
    </>
  );
};

export default FormInfoBox;
