import React, {
  useCallback,
  useEffect,
  useMemo,
  useRef,
  useState,
} from "react";
import { useSelector } from "react-redux";
import cover from "../../assets/images/profile-info-cover.png";
import profile from "../../assets/images/profile.jpg";
import usersService from "../../services/UsersService";
import Icons from "../Helpers/Icons";
import Layout from "../Partials/Layout";
import {
  ChangePasswordTab,
  FaqTab,
  LoginActivityTab,
  NotificationSettingTab,
  PaymentMathodsTab,
  PersonalInfoTab,
  PrivacyPolicyTab,
  TermsConditionTab,
} from "./Tabs";
import RecipientAccountTab from "./Tabs/RecipientAccountTab";

export default function Settings({ faq }) {
  const apiCall = new usersService();
  const { userDetails } = useSelector((state) => state?.userDetails);
  const [profileImg, setProfileImg] = useState(
    userDetails?.profile_pic_url ? userDetails.profile_pic_url : profile
  );
  let [uploadStatus, setUploadStatus] = useState({loading: false, status: false, message:''}) // HOLDS STATE FOR UPLOAD PROFILE PICTURE STATUS
  const [coverImg, setCoverImg] = useState(cover);
  const [reloadCardList, setReloadCardList] = useState(false); // STATE TO DETERMINE WHEN CARD LIST RELOADS. EG: WHEN USER DELETES A CARD

  // profile img
  const profileImgInput = useRef(null);
  const browseProfileImg = () => {
    profileImgInput.current.click();
  };
  const profileImgChangHandler = (e) => {
    // if (e.target.value !== "") {
    //   const imgReader = new FileReader();
    //   imgReader.onload = (event) => {
    //     setProfileImg(event.target.result);
    //   };
    //   imgReader.readAsDataURL(e.target.files[0]);
    // }
    setUploadStatus({loading: false, status: false, message:''})
    let acceptedFormat = ["jpeg", "jpg", "png", "bmp", "gif"] // ARRAY OF SUPPORTED FORMATS
    let uploadedFile = e.target.files[0] //UPLOADED FILE

    if(!acceptedFormat.includes(uploadedFile?.type?.split("/")[1]?.toLowerCase())){ //CHECKING FOR CORRECT UPLOAD FORMAT
      let msg = 'Please select '
      for(let i=0; i<=acceptedFormat.length-1; i++){
        if(i == acceptedFormat.length-1){
          msg+=`or ${acceptedFormat[i]}`
        }else{
          msg+=`${acceptedFormat[i]}, `
        }
      }
      setUploadStatus({loading: false, status: false, message:msg})
      return setTimeout(()=>{
        profileImgInput.current.value = '' // clear the input
        setUploadStatus({loading: false, status: false, message:''})
      },5000)
    }

    if(uploadedFile.size > 5*1048576){ // CHECKING FOR CORRECT FILE SIZE
      setUploadStatus({loading: false, status: false, message:'File must not exceed 5MB'})
      return setTimeout(()=>{
        profileImgInput.current.value = '' // clear the input
        setUploadStatus({loading: false, status: false, message:''})
      },5000)
    }

    if (e.target.value !== "") {
      const imgReader = new FileReader();
      imgReader.onload = (event) => {
        let reqData = { // PAYLOAD FOR API CALL
          file_name: uploadedFile?.name,
          file_size: uploadedFile?.size,
          file_type: uploadedFile?.type?.split("/")[0]?.toLowerCase(),
          file_data: event?.target?.result,
          msg_type: 'FILE',
          action: 'WRENCHBOARD_PICTURE_PROFILE',
          // action: 11307
        }
        setUploadStatus({loading: true, status: false, message:'Loading...'})
        apiCall.sendFiles(reqData).then(res=>{
          if(res.status != 200 || res.data.internal_return < 0){
            return setUploadStatus({loading: false, status: false, message: 'Something went wrong, try again'})
          }
          setUploadStatus({loading: false, status: true, message: 'Uploaded successfully'})
          setProfileImg(event.target.result);
        }).catch(error=>{
          setUploadStatus({loading: false, status: false, message: 'Network error, try again'})
        }).finally(()=>{
          setTimeout(()=>{
            setUploadStatus({loading: false, status: false, message: ''})
          },5000)
        })
      };
      imgReader.readAsDataURL(e.target.files[0]);
    }
  };
  // cover img
  const coverImgInput = useRef(null);
  const browseCoverImg = () => {
    coverImgInput.current.click();
  };
  const coverImgChangHandler = (e) => {
    if (e.target.value !== "") {
      const imgReader = new FileReader();
      imgReader.onload = (event) => {
        setCoverImg(event.target.result);
      };
      imgReader.readAsDataURL(e.target.files[0]);
    }
  };

  // Tabs Handling
  const tabs = [
    {
      id: 1,
      name: "personal",
      title: "Edit Profile",
      iconName: "people-hover",
    },
    {
      id: 2,
      name: "payment",
      title: "Payment Cards",
      iconName: "bank-card",
    },
    {
      id: 3,
      name: "recipients-account",
      title: "Recipients Account",
      iconName: "bank-card",
    },
    {
      id: 4,
      name: "notification",
      title: "Notification Setting",
      iconName: "notification-setting",
    },
    {
      id: 5,
      name: "login_activity",
      title: "Login Activity",
      iconName: "login-activity",
    },
    {
      id: 6,
      name: "password",
      title: "Change Password",
      iconName: "password-hover",
    },
    {
      id: 7,
      name: "faq",
      title: "FAQ",
      iconName: "block-question",
    },
    {
      id: 8,
      name: "privacy",
      title: "Privacy Policy",
      iconName: "page-right",
    },
    {
      id: 9,
      name: "terms",
      title: "Terms and Conditions",
      iconName: "page-right",
    },
  ];
  const [tab, setTab] = useState(tabs[0].name);
  const tabHandler = (value) => {
    setTab(value);
  };

  // Recipient Account
  const [recipientAccount, setRecipientAccount] = useState({
    state: false,
    loader: false,
    msg: "",
    data: null,
  });

  const getRecipientAccount = useCallback(async () => {
    setRecipientAccount((prev) => ({ loader: true }));

    let res;
    try {
      res = await apiCall.getRecipient();
      res = res.data;

      if (res?.internal_return < 0) {
        setRecipientAccount((prev) => ({
          loader: false,
          msg: "Sorry, something went wrong",
        }));
        setTimeout(() => setRecipientAccount((prev) => prev), 5000);
        return;
      }

      return setTimeout(() => {
        setRecipientAccount((prev) => ({ loader: false, data: res }));
      });
    } catch (error) {
      setRecipientAccount((prev) => ({
        loader: false,
        msg: "Sorry, an error occurred",
      }));
      setTimeout(() => setRecipientAccount((prev) => prev), 5000);
      return;
    }
  }, [apiCall]);

  useEffect(() => {
    getRecipientAccount();
  }, [reloadCardList]);

  return (
    <>
      <Layout>
        <div className="settings-wrapper w-full relative mb-10">
          <div className="main-wrapper w-full">
            {/* heading */}
            <div className="heading w-full mb-6">
              <h1 className="text-26 font-bold text-dark-gray dark:text-white antialiased">
                Settings
              </h1>
            </div>
            <div className="content-container w-full pt-10 rounded-2xl bg-white dark:bg-dark-white  ">
              <div className="content-heading w-full mb-8 lg:px-10 px-4">
                <h1 className="text-xl font-bold text-dark-gray dark:text-white antialiased">
                  Personal Information
                </h1>
              </div>
              <div className="content-body w-full lg:flex lg:px-10 px-4">
                <div className="content-tab-items lg:w-[230px] w-full mr-2">
                  <ul className="overflow-hidden mb-10 lg:mb-0">
                    {tabs.map(({ name, id, title, iconName }) => (
                      <li
                        onClick={() => tabHandler(name)}
                        key={id}
                        className={`flex lg:space-x-4 space-x-2 hover:text-purple transition-all duration-300 ease-in-out items-center cursor-pointer lg:mb-11 mb-2 mr-6 lg:mr-0 float-left lg:float-none overflow-hidden ${
                          tab === name ? "text-purple" : " text-thin-light-gray"
                        }`}
                      >
                        <div>
                          <Icons name={iconName} />
                        </div>
                        <div>
                          <p className="text-18 tracking-wide">{title}</p>
                        </div>
                      </li>
                    ))}
                  </ul>
                </div>
                <div className="w-[1px] bg-[#E3E4FE] dark:bg-[#a7a9b533]  mr-10"></div>
                <div className="content-body-items flex-1">
                  {tab === "personal" && (
                    <div className="tab-item">
                      <PersonalInfoTab
                        profileImg={profileImg}
                        coverImg={coverImg}
                        browseProfileImg={browseProfileImg}
                        profileImgInput={profileImgInput}
                        profileImgChangHandler={profileImgChangHandler}
                        coverImgChangHandler={coverImgChangHandler}
                        browseCoverImg={browseCoverImg}
                        coverImgInput={coverImgInput}
                        uploadStatus={uploadStatus}
                      />
                    </div>
                  )}
                  {tab === "payment" && (
                    <div className="tab-item">
                      <PaymentMathodsTab />
                    </div>
                  )}
                  {tab === "recipients-account" && (
                    <div className="tab-item">
                      <RecipientAccountTab
                        recipientAccount={recipientAccount}
                        setRecipientAccount={setRecipientAccount}
                        setReloadCardList={setReloadCardList}
                      />
                    </div>
                  )}
                  {tab === "notification" && (
                    <div className="tab-item">
                      <NotificationSettingTab />
                    </div>
                  )}
                  {tab === "login_activity" && <LoginActivityTab />}
                  {tab === "password" && <ChangePasswordTab />}
                  {tab === "faq" && <FaqTab datas={faq} />}
                  {tab === "privacy" && <PrivacyPolicyTab />}
                  {tab === "terms" && <TermsConditionTab />}
                </div>
              </div>
            </div>
          </div>
        </div>
      </Layout>
    </>
  );
}
