import React, {
  Suspense,
  useCallback,
  useEffect,
  useMemo,
  useState,
} from "react";
import SiteService from "../../services/SiteService";
import InputCom from "../Helpers/Inputs/InputCom";
import ModalCom from "../Helpers/ModalCom";
import Layout from "../Partials/Layout";
import LoadingSpinner from "../Spinners/LoadingSpinner";
import FamilyTable from "./FamilyTable";

export default function FamilyAcc() {
  const [selectTab, setValue] = useState("today");
  // State to store the selected year and month
  const [selectedYear, setSelectedYear] = useState("");
  const [selectedMonth, setSelectedMonth] = useState("");
  const [familyList, setFamilyList] = useState([]);
  const [loader, setLoader] = useState(false);
  const [popUp, setPopUp] = useState(false);
  const [listReload, setListReload] = useState(false);
  const [msgErr, setMsgErr] = useState("");
  const [formData, setFormData] = useState({
    first_name: "",
    last_name: "",
  });

  const apiCall = useMemo(() => new SiteService(), []);

  const popUpHandler = () => {
    setPopUp((prev) => !prev);
  };

  const filterHandler = (value) => {
    setValue(value);
  };

  // Handle year selection
  const handleYearChange = (e) => {
    setSelectedYear(e.target.value);
  };

  // Handle month selection
  const handleMonthChange = (e) => {
    setSelectedMonth(e.target.value);
  };

  const handleInputChange = (event) => {
    const { name, value } = event?.target;
    setFormData((prevFormData) => ({ ...prevFormData, [name]: value }));
  };

  // use the useEffect hook to clear the selected month if the year changes (to ensure consistency)
  useEffect(() => {
    if (selectedYear === "" && selectedMonth !== "") {
      setSelectedMonth("");
    }
  }, [selectedYear]);

  const addMember = async () => {
    const { first_name, last_name } = formData;
    setLoader(true);
    try {
      if (first_name !== "" && last_name !== "") {
        const reqData = {
          firstname: first_name,
          lastname: last_name,
          year: +selectedYear,
          month: +selectedMonth,
        };

        const res = await apiCall.addFamily(reqData);
        const { data } = res;

        if (data?.internal_return > 0 && data?.status === "OK") {
          setLoader(false);
          setListReload((prev) => !prev);
          popUpHandler();
        } else {
          setLoader(false);
          setMsgErr("Sorry, something went wrong");
        }
      } else {
        setLoader(false);
        setMsgErr("Please fill in the fields");
      }
    } catch (error) {
      setLoader(false);
      setMsgErr("An error occurred");
      throw new Error(error);
    } finally {
      setTimeout(() => {
        setMsgErr(null);
      }, Number(process.env.REACT_APP_LOGIN_ERROR_TIMEOUT));
      setFormData({
        first_name: "",
        last_name: "",
      });
      setSelectedMonth("");
      setSelectedYear("");
    }
  };

  const memberList = useCallback(async () => {
    setLoader(true);
    try {
      const reqData = {
        limit: 20,
        offset: 0,
        action: 22010,
      };

      const res = await apiCall.familyListings(reqData);
      const { data } = res;
      if (data?.internal_return >= 0 && data?.status === "OK") {
        const { result_list } = data;
        setFamilyList(result_list);
        setLoader(false);
      } else {
        return;
      }
    } catch (error) {
      setLoader(false);
      throw new Error(error);
    }
  }, [apiCall]);

  useEffect(() => {
    let checkMemberList = true;
    if (checkMemberList) {
      memberList();
    }
    return () => {
      checkMemberList = false;
    };
  }, [listReload, memberList]);

  return (
    <Layout>
      {/*<CommonHead />*/}
      <div className="notification-page w-full mb-10">
        <div className="notification-wrapper w-full">
          {/* heading */}
          <div className="sm:flex justify-between items-center mb-6">
            <div className="mb-5 sm:mb-0">
              <h1 className="text-26 font-bold inline-flex gap-3 text-dark-gray dark:text-white items-center">
                <span
                  className={`${selectTab === "today" ? "block" : "hidden"}`}
                >
                  Family Accounts
                </span>
                {familyList.length < process.env.REACT_APP_MAX_FAMILY_MEMBERS &&
                  !loader && (
                    <button
                      onClick={popUpHandler}
                      type="button"
                      className="text-white btn-gradient text-lg tracking-wide px-5 py-2 rounded-full"
                    >
                      Add
                    </button>
                  )}
              </h1>
            </div>
            <div className="slider-btns flex space-x-4">
              <div
                onClick={() => filterHandler("today")}
                className="relative"
              ></div>
            </div>
          </div>
          <Suspense fallback={<LoadingSpinner color="sky-blue" size="16" />}>
            <FamilyTable
              familyList={familyList}
              loader={loader}
              popUpHandler={popUpHandler}
            />
          </Suspense>
        </div>
      </div>
      {popUp && (
        <ModalCom action={popUpHandler} situation={popUp}>
          <FamilyForm
            popUpHandler={popUpHandler}
            value={formData}
            selectedYear={selectedYear}
            selectedMonth={selectedMonth}
            monthHandler={handleMonthChange}
            yearHandler={handleYearChange}
            inputHandler={handleInputChange}
            msgErr={msgErr}
            onClick={addMember}
            loader={loader}
          />
        </ModalCom>
      )}
    </Layout>
  );
}

const FamilyForm = ({
  value: { first_name, last_name },
  ageValue,
  inputHandler,
  selectedMonth,
  selectedYear,
  monthHandler,
  yearHandler,
  msgErr,
  loader,
  onClick,
  popUpHandler,
}) => {
  return (
    <div className="logout-modal-wrapper lg:w-[460px] h-full lg:h-auto bg-white dark:bg-dark-white lg:rounded-2xl">
      <div className="logout-modal-header w-full flex items-center justify-between lg:px-10 lg:py-8 px-[30px] py-[23px] border-b dark:border-[#5356fb29]  border-light-purple dark:border-[#5356fb29] ">
        <h1 className="text-26 font-bold text-dark-gray dark:text-white tracking-wide">
          Add Members
        </h1>
        <button
          type="button"
          className="text-[#374557] dark:text-red-500"
          onClick={popUpHandler}
        >
          <CloseIcon />
        </button>
      </div>
      <form className="logout-modal-body w-full flex flex-col items-center px-10 py-8 gap-4">
        <InputCom
          placeholder="Firstname"
          label="First Name:"
          name="first_name"
          type="text"
          parentClass="flex items-center gap-1 w-full"
          labelClass="flex-[0.2] mb-0"
          inputClass="flex-[0.8] input-curve lg border border-[#dce4e9]"
          fieldClass="px-2"
          value={first_name}
          inputHandler={inputHandler}
        />
        <InputCom
          placeholder="Lastname"
          label="Last Name:"
          name="last_name"
          type="text"
          parentClass="flex items-center gap-1 w-full"
          labelClass="flex-[0.2] mb-0"
          inputClass="flex-[0.8] input-curve lg border border-[#dce4e9]"
          fieldClass="px-2"
          value={last_name}
          inputHandler={inputHandler}
        />
        <div className="input-com mb-7 flex flex-col gap-1 w-full">
          {/* Age dropdown */}
          <div className="">
            <label
              className="input-label text-[#181c32] dark:text-white text-[15px] font-semibold"
              htmlFor="age-selection"
            >
              Birthday: (Year/Month)
            </label>
          </div>
          <YearMonthDropdowns
            handleMonthChange={monthHandler}
            handleYearChange={yearHandler}
            selectedMonth={selectedMonth}
            selectedYear={selectedYear}
          />
        </div>
        {msgErr && (
          <div className="relative p-4 text-[#912741] bg-[#fcd9e2] border-[#fbc6d3] mb-4 rounded-[0.475rem] text-xs font-light leading-[19.5px]">
            {msgErr}
          </div>
        )}
        <div className="signin-area w-full">
          <div className="flex justify-center">
            <button
              type="button"
              onClick={onClick}
              // className={`rounded-[0.475rem] text-white flex justify-center bg-[#4687ba] hover:bg-[#009ef7] transition-all duration-300 items-center h-[42px] py-[0.8875rem] px-[1.81rem] text-[14.95px] btn-login`}
              className="text-white btn-gradient text-lg tracking-wide px-6 py-2 rounded-full"
            >
              {loader ? (
                <div className="signup btn-loader"></div>
              ) : (
                <span>Add</span>
              )}
            </button>
          </div>
        </div>
      </form>
    </div>
  );
};

const CloseIcon = () => (
  <svg
    width="36"
    height="36"
    viewBox="0 0 36 36"
    fill="none"
    className="fill-current"
    xmlns="http://www.w3.org/2000/svg"
  >
    <path
      d="M36 16.16C36 17.4399 36 18.7199 36 20.0001C35.7911 20.0709 35.8636 20.2554 35.8385 20.4001C34.5321 27.9453 30.246 32.9248 22.9603 35.2822C21.9006 35.6251 20.7753 35.7657 19.6802 35.9997C18.4003 35.9997 17.1204 35.9997 15.8401 35.9997C15.5896 35.7086 15.2189 35.7732 14.9034 35.7093C7.77231 34.2621 3.08728 30.0725 0.769671 23.187C0.435002 22.1926 0.445997 21.1199 0 20.1599C0 18.7198 0 17.2798 0 15.8398C0.291376 15.6195 0.214408 15.2656 0.270759 14.9808C1.71321 7.69774 6.02611 2.99691 13.0428 0.700951C14.0118 0.383805 15.0509 0.386897 15.9999 0C17.2265 0 18.4532 0 19.6799 0C19.7156 0.124041 19.8125 0.136067 19.9225 0.146719C27.3 0.868973 33.5322 6.21922 35.3801 13.427C35.6121 14.3313 35.7945 15.2484 36 16.16ZM33.011 18.0787C33.0433 9.77105 26.3423 3.00309 18.077 2.9945C9.78479 2.98626 3.00344 9.658 2.98523 17.8426C2.96667 26.1633 9.58859 32.9601 17.7602 33.0079C26.197 33.0577 32.9787 26.4186 33.011 18.0787Z"
      fill=""
      fillOpacity="0.6"
    />
    <path
      d="M15.9309 18.023C13.9329 16.037 12.007 14.1207 10.0787 12.2072C9.60071 11.733 9.26398 11.2162 9.51996 10.506C9.945 9.32677 11.1954 9.0811 12.1437 10.0174C13.9067 11.7585 15.6766 13.494 17.385 15.2879C17.9108 15.8401 18.1633 15.7487 18.6375 15.258C20.3586 13.4761 22.1199 11.7327 23.8822 9.99096C24.8175 9.06632 26.1095 9.33639 26.4967 10.517C26.7286 11.2241 26.3919 11.7413 25.9133 12.2178C24.1757 13.9472 22.4477 15.6855 20.7104 17.4148C20.5228 17.6018 20.2964 17.7495 20.0466 17.9485C22.0831 19.974 24.0372 21.8992 25.9689 23.8468C26.9262 24.8119 26.6489 26.1101 25.4336 26.4987C24.712 26.7292 24.2131 26.3441 23.7455 25.8757C21.9945 24.1227 20.2232 22.3892 18.5045 20.6049C18.0698 20.1534 17.8716 20.2269 17.4802 20.6282C15.732 22.4215 13.9493 24.1807 12.1777 25.951C11.7022 26.4262 11.193 26.7471 10.4738 26.4537C9.31345 25.9798 9.06881 24.8398 9.98589 23.8952C11.285 22.5576 12.6138 21.2484 13.9387 19.9355C14.5792 19.3005 15.2399 18.6852 15.9309 18.023Z"
      fill="#"
      fillOpacity="0.6"
    />
  </svg>
);

function YearMonthDropdowns({
  selectedMonth,
  selectedYear,
  handleMonthChange,
  handleYearChange,
}) {
  // Get the current year
  const currentYear = new Date().getFullYear();

  // Generate an array of years from the current year to (currentYear - 19)
  const years = Array.from({ length: 17 }, (_, index) => currentYear - index);

  // Array of month names
  const months = [
    "January",
    "February",
    "March",
    "April",
    "May",
    "June",
    "July",
    "August",
    "September",
    "October",
    "November",
    "December",
  ];

  return (
    <div className="flex max-w-[330px] w-full self-end gap-4">
      <select
        id="yearDropdown"
        value={selectedYear}
        onChange={handleYearChange}
        className="input-wrapper border border-[#f5f8fa] dark:border-[#5e6278] w-56 rounded-[35px] h-10 overflow-hidden relative font-medium leading-6 bg-clip-padding text-[#5e6278] dark:text-gray-100 bg-[#f5f8fa] dark:bg-[#5e6278] text-base focus-visible:border-transparent focus-visible:outline-0 focus-visible:ring-transparent px-4"
        // size="5"
      >
        <option value="">Select a Year</option>
        {years.map((year) => (
          <option key={year} value={year}>
            {year}
          </option>
        ))}
      </select>

      <select
        id="monthDropdown"
        value={selectedMonth}
        onChange={handleMonthChange}
        className="input-wrapper border border-[#f5f8fa] dark:border-[#5e6278] w-56 rounded-[35px] h-10 overflow-hidden relative font-medium leading-6 bg-clip-padding text-[#5e6278] dark:text-gray-100 bg-[#f5f8fa] dark:bg-[#5e6278] text-base focus-visible:border-transparent focus-visible:outline-0 focus-visible:ring-transparent px-4"
        // size="5"
      >
        <option value="">Select a Month</option>
        {months.map((month, index) => (
          <option key={month} value={index + 1}>
            {month}
          </option>
        ))}
      </select>
    </div>
  );
}
