import React, { useState, useRef, useEffect } from 'react';
import { useDispatch, useSelector } from 'react-redux';
import { Messages } from '../../Components/Notifications/Messages';
import { useNavigate } from 'react-router-dom';
import { Form } from 'antd';
import {
  clearSession,
  encryptedValuesUrlFun,
  getSession,
  sessionStore,
} from '../../Services/Others';
import FormHeader from '../PageComponents/FormHeader.jsx';
import { DropDowns } from '../../Components/Forms/DropDown.jsx';
import '../../Styles/UpiDetails/upidetails.scss';
import {
  changeSelectedBranchId,
  changeWarehouse,
  checkSession,
  getCompBranchData,
  getLoginuser,
  PostLoginSuser,
  PUTLoginuser,
} from '../../Features/BrachLogin/BranchLogin.js';
import { gettableData } from '../../Features/PreferenceMaster/PreferenceMaster.js';
import {
  changeOrderCardDetails,
  getPreferenceData,
} from '../../Features/BookingScreen/BookingData/BookingData.js';
import { changeBreadCrumb } from '../../Features/AppPage/CenterPage.js';
import { getTemplate } from '../../Features/ThemeChange/ThemeChange.js';
import { DefaultModal } from '../../Components/Modal/DefaultModal.jsx';
import { RadioGrpButton } from '../../Components/Forms/RadioGroup.jsx';
import { UserDataBasedOnBranchId } from '../../Features/Reports/Reports.js';
import {
  GLobalSadminUserPin,
  GLobalSadminUserData,
} from '../../Features/BrachLogin/BranchLogin';
import { BsShopWindow } from 'react-icons/bs';

const subDirectory = import.meta.env.BASE_URL;
const BranchLogin = () => {
  const formRef = useRef(null);
  const dispatch = useDispatch();
  const navigate = useNavigate();

  const [messageType, setMessageType] = useState(null);
  const [messageData, setMessageData] = useState(null);
  const [modal, setModal] = useState(false);
  const [SelectType, setSelectType] = useState('O');
  const [SelectTypeName, setSelectTypeName] = useState('OTP');
  const [pinInput, setpinInput] = useState(false);
  const [otp, setOtp] = useState();
  const [FirstTimeOtp, setFirstTimeOtp] = useState(false);
  const [FirstTimePin, setFirstTimePin] = useState(false);

  const [seconds, setSeconds] = useState(0);
  const [disabled, setDisabled] = useState(false);
  const clicked = useRef(false);
  const timerDuration = 30;

  const [seletedBranchData, setseletedBranchData] = useState();
  const [CompBranchData, setCompBranchData] = useState();
  const [UserType, setUserType] = useState(
    getSession('UserType') ? getSession('UserType') : 'Super Admin'
  );
  const CompId = getSession('CompId');
  const AppId = getSession('AppId');
  const UserId = getSession('UserId');
  const sessionId = getSession('SessionId');
  const inputRefs = useRef([]);
  const [pin, setPin] = useState(['', '', '', '']);
  const [aftergetPin, setAftergetPin] = useState(false);
  const [selectedUserData, setSelectedUserData] = useState(null);
  const [userDropDown, setuserDropDown] = useState([]);
  const SAdminuserPin = useSelector(GLobalSadminUserPin);
  const SAdminUserData = useSelector(GLobalSadminUserData);

  useEffect(() => {
    inputRefs?.current[0]?.focus(); // Focus first input on mount
  }, []);
  const items = [
    {
      name: 'Home',
      link: `${subDirectory}app-page/home`,
    },
  ];

  useEffect(() => {
    fetchBranchData(); // Call the async function immediately
    dispatch(changeBreadCrumb({ items: items }));
    if (UserType != 'Super Admin User') {
      setAftergetPin(true);
    }
  }, []);
  useEffect(() => {
    if (aftergetPin == true && UserType == 'Super Admin User') {
      fetchData(seletedBranchData);
    }
  }, [aftergetPin]);

  useEffect(() => {
    let interval = null;

    if (disabled && seconds > 0) {
      interval = setInterval(() => {
        setSeconds((prev) => prev - 1);
      }, 1000);
    } else if (seconds === 0) {
      setDisabled(false);
      clicked.current = false; // Enable button after timer ends
      // Enable button after timer ends
    }

    return () => {
      if (interval) clearInterval(interval);
    };
  }, [seconds, disabled]);

  const fetchData = async (e, type) => {
    await sessionStore('BranchId', e);
    let data = {
      CompId: CompId,
      BranchId: e,
      AppId: AppId,
      UserId: UserId,
    };

    let res = await dispatch(getPreferenceData(data)).unwrap();
    await dispatch(
      getTemplate({ CompId: CompId, BranchId: e, AppId: AppId })
    ).unwrap();
    const filterSettingIdName = 'Dashboard';

    const filteredDatas = res?.data?.data?.[0]?.SettingDtlDetails?.filter(
      (item) => item.SettingIdName === filterSettingIdName
    );

    if (res?.data?.statusCode == 1 && type !== 'W') {
      filteredDatas?.[0]?.SettingValue == 'Y'
        ? navigate(`${subDirectory}app-page/home`)
        : navigate(`${subDirectory}sales`);
    } else {
      navigate(`${subDirectory}app-page/home`);
    }
  };
  const fetchBranchData = async () => {
    if (UserType === 'Super Admin' || UserType === 'Super Admin User') {
      const response = await dispatch(
        getCompBranchData({ CompId: CompId, AppId: AppId })
      ).unwrap();
      if (response?.data?.statusCode === 1) {
        setCompBranchData(response?.data?.data);
      } else {
        setMessageType('error');
        setMessageData(response?.data?.response);
      }
    } else if (UserType === 'Admin' || UserType === 'Admin User') {
      const response = await dispatch(
        getCompBranchData({ AppId: AppId, UserId: UserId, CompId: CompId })
      ).unwrap();
      if (response?.data?.statusCode === 1) {
        setCompBranchData(response?.data?.data);
      } else {
        setMessageType('error');
        setMessageData(response?.data?.response);
      }
    }
  };
  useEffect(() => {
    if (CompBranchData?.length == 1) {
      if (UserType != 'Super Admin User') {
        fetchData(CompBranchData[0]?.BrId);
      } else {
        const checkData = SAdminUserData?.filter(
          (item) =>
            item?.AppId == AppId &&
            item?.CompId == CompId &&
            item?.BranchId == CompBranchData[0]?.BrId
        );
        if (
          UserType == 'Super Admin User' &&
          (checkData?.length == 0 || checkData?.[0]?.Status !== 'Y')
        ) {
          userDropData(CompBranchData[0]?.BrId);
          setModal(true);
        } else {
          setAftergetPin(true);
        }
      }
    }
  }, [CompBranchData]);

  const onChangeBranch = async (e) => {
    let data = CompBranchData?.find((a) => a?.BrId == e);
    if (data?.LocationType == 'W') {
      sessionStore("Warehouse", true)
      await dispatch(changeWarehouse(true));
    }
    else {
      sessionStore("Warehouse", false)
      await dispatch(changeWarehouse(false));
    }

    setseletedBranchData(e);
    dispatch(changeSelectedBranchId(e));

    await sessionStore('BranchId', e);

    dispatch(changeOrderCardDetails([]));
    if (UserType != 'Super Admin User') {
      await fetchData(e, data?.LocationType);
    } else {
      const checkData = SAdminUserData?.filter(
        (item) =>
          item?.AppId == AppId && item?.CompId == CompId && item?.BranchId == e
      );
      if (
        UserType == 'Super Admin User' &&
        (checkData?.length == 0 || checkData?.[0]?.Status !== 'Y')
      ) {
        userDropData(e);
        setModal(true);
      } else {
        setAftergetPin(true);
      }
    }
  };

  const handleSubmit = async (enteredPin) => {
    if (otp == Number(enteredPin)) {
      let data = {
        CompId: CompId,
        BranchId: seletedBranchData,
        AppId: AppId,
        UserId: UserId,
        SignInType: SelectTypeName,
        SecurityCode: Number(enteredPin),
        UpdatedBy: UserId,
        SessionId: sessionId,
        EmpId: selectedUserData,
      };
      let response = await dispatch(PUTLoginuser(data)).unwrap();
      if (response?.data?.statusCode == 1) {
        await dispatch(checkSession({ UserId, sessionId })).unwrap();
        setModal(false);
        setAftergetPin(true);
        inputRefs?.current?.forEach((ref) => {
          if (ref) {
            ref.value = '';
          }
        });
        setPin(['', '', '', '']);
      }
    } else {
      alert(`Invalid  ${SelectType == 'O' ? 'OTP' : 'Pin'}`);
    }
  };
  const handleChange = (index, event) => {
    const value = event.target.value;

    if (/^\d$/.test(value)) {
      const newPin = [...pin];
      newPin[index] = value;
      setPin(newPin);

      if (index < inputRefs?.current?.length - 1) {
        inputRefs?.current[index + 1]?.focus(); // Move to next input
      }

      if (newPin.every((num) => num !== '')) {
        handleSubmit(newPin.join('')); // Call function when all 4 digits are entered
      } // Call function when all 4 digits are entered
    } else {
      event.target.value = '';
      const newPin = [...pin];
      newPin[index] = value;
      setPin(newPin); // Clear input if more than one digit is entered
    }
  };

  const sentpinfn = async () => {
    let data = {
      CompId: CompId,
      BranchId: seletedBranchData,
      AppId: AppId,
      UserId: UserId,
      SignInType: SelectTypeName,
      CreatedBy: UserId,
      EmpId: selectedUserData,
    };

    let response = await dispatch(PostLoginSuser(data)).unwrap();

    if (response?.data?.statusCode == 1) {
      setOtp(response?.data?.OTP || response?.data?.PIN);
      setpinInput(true); // Show PIN/OTP input fields
      setSeconds(timerDuration); // Start the countdown timer
      setDisabled(true); // Disable the button temporarily
      console.log('OTP Sent!');
      if (SelectTypeName === 'OTP') {
        setFirstTimeOtp(true); // Set OTP as sent
      } else {
        setFirstTimePin(true); // Set PIN as sent
      }
    }
  };
  const handleClick = () => {
    if (selectedUserData) {
      if (clicked.current) return;
      clicked.current = true;
      if (seconds === 0) {
        sentpinfn(); // Resend PIN/OTP after 30 seconds
      }
      inputRefs?.current?.forEach((ref) => {
        if (ref) {
          ref.value = ''; // Reset the value of each input
        }
      });
      setPin(['', '', '', '']);
    } else {
      alert('Please select user');
    }
  };

  const ChangeMethod = (e) => {
    setSelectType(e);
    setSelectTypeName(e === 'O' ? 'OTP' : 'PIN');
  };
  const userDropData = async (e) => {
    const gettinguserDropDown = await dispatch(
      UserDataBasedOnBranchId(e)
    ).unwrap();
    if (gettinguserDropDown?.data?.statusCode === 1) {
      let finaluserDropDown = gettinguserDropDown?.data?.data?.filter(
        (value) => value.ActiveStatus === 'A'
      );
      setuserDropDown(finaluserDropDown);
    }
  };
  const UserDropDownChange = async (e) => {
    setSelectedUserData(e);
  };
  const handlePageChange = async () => {
    console.log('i am called', CompBranchData);

    if (CompBranchData?.length === 1) {
      const commonUrl = import.meta.env.ENV_COMMON_BASE_URL;

      const MobileNo = encryptedValuesUrlFun(getSession('MobileNo'));
      const userName = encryptedValuesUrlFun(getSession('userName'));
      const UserId = encryptedValuesUrlFun(getSession('UserId'));
      const UserType = encryptedValuesUrlFun(getSession('UserType'));
      const CompId = encryptedValuesUrlFun(getSession('CompId'));
      const CompName = encryptedValuesUrlFun(getSession('CompName'));
      const SessionId = encryptedValuesUrlFun(getSession('SessionId'));

      if (sessionStorage.getItem('BranchId') !== null) {
        clearSession('BranchId');
      }
      if (sessionStorage.getItem('AppId') !== null) {
        clearSession('AppId');
      }

      const param = {
        MN: MobileNo,
        UN: userName,
        UD: UserId,
        UT: UserType,
        CD: CompId,
        CN: CompName,
        SD: SessionId,
      };

      const queryParams = new URLSearchParams(param).toString();
      window.location.replace(
        `${commonUrl}/home/landing-page/home?${queryParams}`
      );
    } else {
      setseletedBranchData();
      if (sessionStorage.getItem('BranchId') !== null) {
        clearSession('BranchId');
      }
      navigate(`${subDirectory}app-page/branch-login`);
    }
    if (sessionStorage.getItem('hasRefreshed') !== null) {
      sessionStorage.removeItem('hasRefreshed');
    }

    setModal(false);
  };
  return (
    <>
      <div className="pageOverAll">
        <div className="userPage">
          <div className="formName">
            <FormHeader title={'Branch Signin'} />
          </div>
          {/* <div className="userPageContent">
            <Messages messageType={messageType} messageData={messageData} />
            <div className="formDXiv">
              <Form
                ref={formRef}
                // onFinish={onFinish}
                // initialValue={editstate }
              >
                <div>
                  <Form.Item
                    name="Branch"
                    rules={[
                      {
                        required: true,
                        pattern: /^(?!\s*$).+/,
                        message: 'Please Enter Branch',
                      },
                    ]}
                  >
                    <DropDowns
                      options={CompBranchData?.map((option) => ({
                        value: option.BrId,
                        label:
                          option?.LocationType == 'W'
                            ? option.IndividualBrName + ' (Ware house) '
                            : option.BrName,
                      }))}
                      label={<label class="required">Branch</label>}
                      className="field-DropDown"
                      onChangeFunction={(e) => onChangeBranch(e)}
                      valueData={seletedBranchData}
                    />
                  </Form.Item>
                </div>
              </Form>
            </div>
          </div> */}
          {/* New Design for Branch Login */}
          <div className="branchLoginMaster">
            {CompBranchData?.map((branch) => (
              <div
                key={branch.BrId}
                style={{ cursor: 'pointer' }}
                className={
                  branch?.LocationType === 'W'
                    ? 'GodownLoginCard'
                    : 'brachLoginCard'
                }
                onClick={(e) => {
                  e.stopPropagation();
                  onChangeBranch(branch?.BrId);
                }}
              >
                <div className="branchLoginCardContent">
                  {branch?.LocationType === 'W' ? (
                    <div className="GodownLoginIcon">
                      <BsShopWindow />
                    </div>
                  ) : (
                    <div className="branchLoginStoreIcon">
                      <BsShopWindow />
                    </div>
                  )}
                  <div className="brachloginStoreName">
                    {branch?.LocationType == 'W'
                      ? branch?.IndividualBrName + ' (Ware house) '
                      : branch?.BrName}
                  </div>
                  <div className="branchLoginAddress">
                    {branch?.BrCity} - {branch?.BrZip}
                  </div>
                  <div className="branchLoginCreateddate">
                    Created Date :{' '}
                    {(() => {
                      const date = new Date(branch?.CreatedDate);
                      const day = date.getDate().toString().padStart(2, '0');
                      const month = date.toLocaleDateString('en-US', {
                        month: 'short',
                      });
                      const year = date.getFullYear();
                      return `${day} / ${month} / ${year}`;
                    })()}
                  </div>
                </div>
                <button
                  // className="openBrachBTN openGodownBTN"
                  className={
                    branch?.LocationType === 'W'
                      ? 'openGodownBTN'
                      : 'openBrachBTN'
                  }
                // onClick={() => onChangeBranch(branch?.BrId)}
                >
                  {branch?.LocationType === 'W'
                    ? 'Open Warehouse'
                    : 'Open Branch '}
                </button>
              </div>
            ))}
          </div>
        </div>
      </div>

      <DefaultModal
        open={modal}
        title="Authentication"
        width={500}
        handleCancel={handlePageChange}
        footer={false}
        children={
          <>
            <div className="modalContentsadminuser">
              <DropDowns
                options={userDropDown?.map((option) => ({
                  value: option?.UserId,
                  label: option?.UserName,
                }))}
                label={<label className="required">User Name</label>}
                className="field-DropDown"
                onChangeFunction={(e) => UserDropDownChange(e)}
                isOnchanges={selectedUserData ? true : false}
                valueData={selectedUserData}
                disabled={disabled}
              />
              <div style={{ display: 'flex', justifyContent: 'space-between' }}>
                <div className="RadioButton">
                  <RadioGrpButton
                    content={[
                      { value: 'O', label: 'OTP' },
                      { value: 'P', label: 'PIN' },
                    ]}
                    fieldState={true}
                    defaultSelect={SelectType}
                    onSelectFuntion={(e) => ChangeMethod(e)}
                  />
                </div>
              </div>

              {pinInput && (
                <div className="otpInputsadminuser">
                  {[0, 1, 2, 3].map((i) => (
                    <input
                      key={i}
                      ref={(el) => (inputRefs.current[i] = el)}
                      className="inputNumber"
                      type="text"
                      inputMode="numeric"
                      pattern="[0-9]"
                      maxLength={1}
                      onChange={(e) => handleChange(i, e)}
                      onKeyDown={(e) => handleKeyDown(i, e)}
                      style={{
                        textAlign: 'center',
                        width: '40px',
                        fontSize: '20px',
                      }}
                    />
                  ))}
                </div>
              )}

              <div
                style={{
                  width: '100%',
                  display: 'flex',
                  justifyContent: 'flex-end',
                }}
              >
                <button
                  className="size-save-button-retail"
                  onClick={handleClick}
                  disabled={disabled}
                >
                  {SelectTypeName === 'OTP'
                    ? !FirstTimeOtp
                      ? `send ${SelectTypeName.toLocaleLowerCase()}`
                      : `resend ${SelectTypeName.toLocaleLowerCase()}${seconds > 0 ? ` in ${seconds}s` : ''
                      }`
                    : !FirstTimePin
                      ? `send ${SelectTypeName.toLocaleLowerCase()}`
                      : `resend ${SelectTypeName.toLocaleLowerCase()}${seconds > 0 ? ` in ${seconds}s` : ''
                      }`}
                </button>
              </div>
            </div>
          </>
        }
      />
    </>
  );
};
export default BranchLogin;
