import React, { useCallback, useEffect, useId, useMemo, useState } from "react";
import CustomPopUp from "../Helpers/CustomPopUp";
import InputCom from "../Helpers/Inputs/InputCom";
import Layout from "../Partials/Layout";
import FamilyTable from "./FamilyTable";
import SiteService from "../../services/SiteService";

export default function FamilyAcc() {
  const [selectTab, setValue] = useState("today");
  const [selectedAge, setSelectedAge] = useState(undefined);
  const [familyList, setFamilyList] = useState([]);
  const [isOpen, setIsOpen] = useState(false);
  const [loader, setLoader] = useState(false);
  const [msgErr, setMsgErr] = useState("");
  const [formData, setFormData] = useState({
    first_name: "",
    last_name: "",
  });

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

  //   tab handler
  const filterHandler = (value) => {
    setValue(value);
  };

  let id = useId();
  //   For the age drop down
  let startAge = 5;
  let endAge = 16;
  // creates an array of age values ranging from 16 to 70
  const ageRange = Array.from(
    { length: endAge - startAge + 1 },
    (_, index) => startAge + index
  );
  // age handler
  const handleAgeSelect = (event) => {
    setSelectedAge(parseInt(event.target.value));
  };
  //   Input handler
  const handleInputChange = (event) => {
    const { name, value } = event?.target;
    setFormData({ ...formData, [name]: value });
  };

  //   Add member
  const addMember = async () => {
    const { first_name, last_name } = formData;
    setLoader(true);
    try {
      if (first_name !== "" && last_name !== "") {
        let reqData = {
          member_id: localStorage.getItem("member_id"),
          uid: localStorage.getItem("uid"),
          session_id: localStorage.getItem("session_token"),
          firstname: first_name,
          lastname: last_name,
          age: selectedAge,
        };
        console.log(reqData);
        let res = await apiCall.addFamily(reqData);
        const { data } = res;
        if (data?.internal_return > 0 && data?.status == "OK") {
          setLoader(false);
          setIsOpen(false);
        } 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));
    }
  };

  useEffect(() => {
    // member listing
    const memberList = async () => {
      try {
        let reqData = {
          member_id: localStorage.getItem("member_id"),
          uid: localStorage.getItem("uid"),
          sessionid: localStorage.getItem("session_token"),
          limit: 20,
          offset: 0,
          action: 22010,
        };

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

  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-2 text-dark-gray dark:text-white">
                <span
                  className={`${selectTab === "today" ? "block" : "hidden"}`}
                >
                  Family Accounts
                </span>
                <CustomPopUp
                  name="(Add)"
                  btn_class="text-purple"
                  key={id}
                  title="Add members"
                  isOpen={isOpen}
                  setIsOpen={setIsOpen}
                >
                  <FamilyForm
                    value={formData}
                    ageHandler={handleAgeSelect}
                    ageRange={ageRange}
                    ageValue={selectedAge}
                    inputHandler={handleInputChange}
                    msgErr={msgErr}
                    onClick={addMember}
                    loader={loader}
                  />
                </CustomPopUp>
              </h1>
            </div>
            <div className="slider-btns flex space-x-4">
              <div
                onClick={() => filterHandler("today")}
                className="relative"
              ></div>
            </div>
          </div>
          <FamilyTable familyList={familyList} />
        </div>
      </div>
    </Layout>
  );
}

const FamilyForm = ({
  value: { first_name, last_name },
  ageValue,
  inputHandler,
  ageHandler,
  ageRange,
  msgErr,
  loader,
  onClick,
}) => {
  return (
    <div className="w-full relative block ">
      <form className="flex flex-col gap-4">
        <InputCom
          placeholder="Firstname"
          label="First Name:"
          name="first_name"
          type="text"
          parentClass="flex items-center gap-1"
          labelClass="flex-[0.2] mb-0"
          inputClass="flex-[0.8]"
          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"
          labelClass="flex-[0.2] mb-0"
          inputClass="flex-[0.8]"
          fieldClass="px-2"
          value={last_name}
          inputHandler={inputHandler}
        />
        <div className="input-com mb-7 flex gap-1 items-center">
          {/* Age dropdown */}
          <div className="flex items-center justify-between flex-[0.3]">
            <label
              className="input-label text-[#181c32] dark:text-white text-[15px] font-semibold"
              htmlFor="age-selection"
            >
              Select your age:
            </label>
          </div>
          <div className=" flex-[0.7]">
            <select
              name="age-selection"
              id="age-selection"
              className="input-wrapper border border-[#f5f8fa]] dark:border-[#5e6278] w-full rounded-[0.475rem] h-[42px] 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-2"
              onChange={ageHandler}
              value={ageValue}
            >
              <option value={""}>Select your age</option>
              {ageRange?.length > 0 &&
                ageRange?.map((age) => (
                  <option value={age} key={age}>
                    {age}
                  </option>
                ))}
            </select>
          </div>
        </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">
          <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`}
            >
              {loader ? (
                <div className="signup btn-loader"></div>
              ) : (
                <span>Add</span>
              )}
            </button>
          </div>
        </div>
      </form>
    </div>
  );
};
