import { useEffect, useState } from 'react';
import { useSelector, useDispatch } from 'react-redux';
import axios from 'axios';
import { Skeleton } from 'antd';
import KioseTheme1 from './KioskThemes/KioskTheme1.jsx';
import KioseTheme2 from './KioskThemes/KioskTheme2.jsx';
import KioseTheme3 from './KioskThemes/KioskTheme3.jsx';
import notAllowed from '../../Images/notAllowed.jpg';
import {
  decryptedValuesFun,
  getSession,
  sessionStore,
} from '../../Services/Others';
import {
  getProductCategories,
  getCompanyData,
  getAllApplications,
  getDeviceAccess,
  changePaymentgatewayRedirect,
  changePGFailedTransId,
  changePGFailedAmt,
  getProductCardListKiosk,
} from '../../Features/BookingScreen/BookingData/KioskBookingData';
import {
  getKioskTemplateData,
  getKioskTemplate,
  changeKioskPageName,
  changeKioskCustomerMobileNo,
  getKioskPrinterDetails,
} from '../../Features/Kiosk/kiosk';
import '../../Styles/Kiosk/KioskBookingPage.scss';
import { InfoCircleOutlined } from '@ant-design/icons';
import { getPreferenceData } from '../../Features/BookingScreen/BookingData/BookingData.js';

const apiUrlToken = import.meta.env.ENV_API_URL_TOKEN;

const KioskBookingPage = () => {
  const dispatch = useDispatch();
  const kioskTemplateData = useSelector(getKioskTemplateData);
  console.log(kioskTemplateData, 'kioskTemplateData');
  const [devicePresent, setDevicePresent] = useState(false);
  const [deviceAccess, setDeviceAccess] = useState(true);
  const [deviceAddress, setDeviceAddress] = useState(null);
  const [showInfoValues, setShowInfo] = useState(false);
  const CompId = getSession('CompId');
  const BranchId = getSession('BranchId');
  const AppId = getSession('AppId');
  const UserId = getSession('UserId');
  const CompName = getSession('CompName');
  const AppName = getSession('AppName');
  const userName = getSession('userName');
  const MobileNo = getSession('MobileNo');
  const AuthToken = getSession('auth')
  const SessionDtl = {
    CompId: CompId,
    BranchId: BranchId,
    AppId: AppId,
    UserId: UserId,
    CompName: CompName,
    AppName: AppName,
    userName: userName,
    MobileNo: MobileNo,
    AuthToken: AuthToken,
    SessionMobileNo: MobileNo
  };

  useEffect(() => {


    fetchData();
  }, []);

  const fetchData = async () => {
    dispatch(getPreferenceData({
      CompId: SessionDtl?.CompId,
      BranchId: SessionDtl?.BranchId,
      AppId: SessionDtl?.AppId,
      UserId: SessionDtl?.UserId,
    })).unwrap();
    const queryParams = await getQueryParams();

    console.log('queryParams', queryParams);
    if (Object.keys(queryParams)?.length !== 0) {
      console.log('queryParams', queryParams);
      if (!getSession('auth')) {
        let data = {
          username: '1000000001',
          password: '1234',
        };
        const response = await axios.post(
          `${apiUrlToken}/jwtTokenGenerator`,
          data,
          {
            headers: {
              'Content-Type': 'application/json',
              Accept: 'application/json',
            },
          }
        );

        const { token } = response?.data;
        sessionStore('auth', token);
        sessionStore('LoginType', 'Kiosk');
      }
      const MACAddress = queryParams?.MD;
      if (MACAddress) {
        console.log('MACAddress', MACAddress);
        setDeviceAddress(MACAddress);
        setDevicePresent(true);
        let deviceMACResponse = await dispatch(
          getDeviceAccess({ DeviceAddress: MACAddress })
        ).unwrap();
        if (
          deviceMACResponse?.data?.statusCode == 1 &&
          deviceMACResponse?.data?.data?.length > 0 &&
          deviceMACResponse?.data?.data?.[0]?.KioskStatus === 'Y'
        ) {
          setDeviceAccess(true);
          let responseData = deviceMACResponse?.data?.data?.[0];
          responseData?.accessToken != null &&
            responseData?.accessToken != undefined &&
            sessionStore('auth', responseData?.accessToken);
          responseData?.MobileNo != null &&
            responseData?.MobileNo != undefined &&
            sessionStore('MobileNo', responseData?.MobileNo);
          responseData?.UserId != null &&
            responseData?.UserId != undefined &&
            sessionStore('UserId', responseData?.UserId);
          responseData?.UserType != null &&
            responseData?.UserType != undefined &&
            sessionStore('UserType', responseData?.UserType);
          responseData?.CompId != null &&
            responseData?.CompId != undefined &&
            sessionStore('CompId', responseData?.CompId);
          responseData?.CompName != null &&
            responseData?.CompName != undefined &&
            sessionStore('CompName', responseData?.CompName);
          responseData?.AppId != null &&
            responseData?.AppId != undefined &&
            sessionStore('AppId', responseData?.AppId);
          responseData?.AppName != null &&
            responseData?.AppName != undefined &&
            sessionStore('AppName', responseData?.AppName);
          responseData?.BranchId != null &&
            responseData?.BranchId != undefined &&
            sessionStore('BranchId', responseData?.BranchId);
          responseData?.userName != null &&
            responseData?.userName != undefined &&
            sessionStore('userName', responseData?.UserName);
          responseData?.SessionId != null &&
            responseData?.SessionId != undefined &&
            sessionStore('SessionId', responseData?.SessionId);
          responseData?.DeviceAddress != null &&
            responseData?.DeviceAddress != undefined &&
            sessionStore('DeviceAddress', MACAddress);
          sessionStore('hasRefreshed', true);
          dispatch(
            getKioskTemplate({
              CompId: responseData?.CompId,
              BranchId: responseData?.BranchId,
              AppId: responseData?.AppId,
            })
          ).unwrap();
          dispatch(getKioskPrinterDetails({
            CompId: responseData?.CompId,
            BranchId: responseData?.BranchId,
            AppId: responseData?.AppId,
            DeviceMacAddress: MACAddress
          })).unwrap();

          dispatch(getPreferenceData({
            CompId: responseData?.CompId,
            BranchId: responseData?.BranchId,
            AppId: responseData?.AppId,
            UserId: responseData?.UserId,
          })).unwrap();
          dispatch(
            getProductCategories({
              CompId: responseData?.CompId,
              BranchId: responseData?.BranchId,
              AppId: responseData?.AppId,
            })
          ).unwrap();
        } else {
          setDeviceAccess(false);
        }
      } else {
        const MobileNoValue = decryptedValuesFun(queryParams?.MN);
        const UserIdValue = decryptedValuesFun(queryParams?.UD);
        const UserTypeValue = decryptedValuesFun(queryParams?.UT);
        const CompIdValue = decryptedValuesFun(queryParams?.CD);
        const AppIdValue = decryptedValuesFun(queryParams?.AD);
        const BranchIdValue = decryptedValuesFun(queryParams?.BD);
        const OrderIdValue = decryptedValuesFun(queryParams?.OD);
        const AmountValue = decryptedValuesFun(queryParams?.AM);
        let CompNameValue = null,
          AppNameValue = null;
        if (CompIdValue) {
          let response = await dispatch(
            getCompanyData({ CompId: CompIdValue })
          ).unwrap();
          if (response?.data?.statusCode == 1) {
            CompNameValue = response?.data?.data?.[0]?.['CompName'];
          } else {
            CompNameValue = null;
          }
        }
        if (AppIdValue) {
          let appResponse = await dispatch(
            getAllApplications({ AppId: AppIdValue })
          ).unwrap();
          if (appResponse?.data?.statusCode == 1) {
            AppNameValue = appResponse?.data?.data?.[0]?.['AppName'];
          } else {
            AppNameValue = null;
          }
        }
        let userNameValue = null;
        if (queryParams?.UN != null && queryParams?.UN != undefined) {
          userNameValue = decryptedValuesFun(queryParams?.UN);
        }
        console.log(
          'queryParams',
          MobileNoValue,
          UserIdValue,
          UserTypeValue,
          CompIdValue,
          AppIdValue,
          BranchIdValue
        );
        if (
          MobileNoValue &&
          UserIdValue &&
          UserTypeValue &&
          CompIdValue &&
          AppIdValue &&
          BranchIdValue
        ) {
          sessionStore('MobileNo', MobileNoValue);
          sessionStore('UserId', UserIdValue);
          sessionStore('UserType', UserTypeValue);
          sessionStore('CompId', CompIdValue);
          sessionStore('CompName', CompNameValue);
          sessionStore('AppId', AppIdValue);
          sessionStore('AppName', AppNameValue);
          sessionStore('BranchId', BranchIdValue);
          if (userNameValue != null) {
            sessionStore('userName', userNameValue);
          }
          dispatch(
            getKioskTemplate({
              CompId: CompIdValue,
              BranchId: BranchIdValue,
              AppId: AppIdValue,
            })
          ).unwrap();
          dispatch(
            getProductCategories({
              CompId: CompIdValue,
              BranchId: BranchIdValue,
              AppId: AppIdValue,
            })
          ).unwrap();
          dispatch(changeKioskPageName('OrderView'));
          dispatch(changePaymentgatewayRedirect(true));
          dispatch(changeKioskCustomerMobileNo(MobileNoValue));
          dispatch(changePGFailedTransId(OrderIdValue));
          dispatch(changePGFailedAmt(AmountValue));
          const url = new URL(window.location);
          url.search = '';
          window.history.replaceState({}, document.title, url.toString());
        } else {
          console.error('One or more decrypted values are null.');
        }
      }
    } else {
      dispatch(
        getKioskTemplate({ CompId: CompId, BranchId: BranchId, AppId: AppId })
      ).unwrap();
      let Response = await dispatch(
        getProductCategories({
          CompId: CompId,
          BranchId: BranchId,
          AppId: AppId,
        })
      ).unwrap();

      if (Response?.data?.statusCode == 1) {
        dispatch(
          getProductCardListKiosk({
            CompId: CompId,
            BranchId: BranchId,
            AppId: AppId,
            ProdCat: Response?.data?.data?.[0]?.ProdCat,
          })
        );

      }
    }
  };
  function getQueryParams() {
    const searchParams = window.location.search;
    console.log('searchParams', searchParams);
    if (!searchParams) {
      return {};
    }
    const queryParams = new URLSearchParams(searchParams);
    const params = {};
    for (const [key, value] of queryParams.entries()) {
      params[key] = value;
    }
    return params;
  }
  // const kioskTemplateData = {
  //   "KioskHomePage": ["HomePage3"],
  //   "KioskCategory": ["Category3"],
  //   "KioskCard":["Card1"],
  //   "KioskOrderCart":["OrderCart3"],
  //   "KioskOrderPage":["OrderPage3"],
  //   "CompLogo": "https://api.pozo.app/pozo-common-image-api/upload?fileId=658ad4ba662828971bd41b14.png",
  //   "BranchName": "Sri Hari bakery"
  // }
  const showInfo = () => {
    setShowInfo(!showInfoValues);
  };
  const accessCheck = () => {
    if (devicePresent && !deviceAccess) {
      return (
        <>
          <div className="accessDenied">
            <div>
              <img src={notAllowed} alt="notAllowed" width={250} />
            </div>

            <div
              style={{
                display: 'flex',
                gap: '1rem',
                cursor: 'pointer',
                float: 'right',
              }}
            >
              <div>Contact Admin</div>
              <div onClick={showInfo}>
                <InfoCircleOutlined />
              </div>
            </div>
            {showInfoValues && (
              <div style={{ color: 'red' }}>{deviceAddress}</div>
            )}
          </div>
        </>
      );
    } else {
      return (
        <div>
          <Skeleton active />
        </div>
      );
    }
  };
  return (
    <>
      <div className="KioskBookingPage-Container">
        {Object.keys(kioskTemplateData)?.length > 0 ? (
          <>
            {kioskTemplateData?.KioskCategory?.[0] == 'Category1' && (
              <KioseTheme1
                data={kioskTemplateData}
                SessionDtl={SessionDtl}
                devicePresent={devicePresent}
                deviceAccess={deviceAccess}
              />
            )}
            {kioskTemplateData?.KioskCategory?.[0] == 'Category2' && (
              <KioseTheme2
                data={kioskTemplateData}
                SessionDtl={SessionDtl}
                devicePresent={devicePresent}
                deviceAccess={deviceAccess}
              />
            )}
            {kioskTemplateData?.KioskCategory?.[0] == 'Category3' && (
              <KioseTheme3
                data={kioskTemplateData}
                SessionDtl={SessionDtl}
                devicePresent={devicePresent}
                deviceAccess={deviceAccess}
              />
            )}
          </>
        ) : (
          <div>
            {/* <Skeleton active /> */}

            {accessCheck()}
          </div>
        )}
      </div>
    </>
  );
};

export default KioskBookingPage;
