import { useEffect, useRef, useState } from 'react';
import { useSelector, useDispatch } from 'react-redux';
import { Button, Carousel, Skeleton } from 'antd';
import { ArrowRightOutlined, LeftOutlined, RightOutlined } from '@ant-design/icons';
import SelectionComponent from './SelectionComponent';
import PreviewLayout1 from '../PreviewLayouts/PreviewLayout1';
import PreviewLayout2 from '../PreviewLayouts/PreviewLayout2';
import PreviewLayout3 from '../PreviewLayouts/PreviewLayout3';
import PreViewLayout4 from '../PreviewLayouts/PreViewLayout4';
import PreviewLayout5 from '../PreviewLayouts/PreviewLayout5';
import PreViewLayout6 from '../PreviewLayouts/PreViewLayout6';
import ComboLayout1 from '../PreviewLayouts/ComboLayout1';
import { changeActiveTheme, changeOthersTheme, changeSelectedTheme, changeThemeCreation, getOthersTemplate, getPreviewData, getTemplate, GlobalActiveTheme, GlobalDefaultTheme, GlobalOthersTheme, GlobalSelectedTheme } from '../../../../Features/ThemeChange/ThemeChange';
import '../../../../Styles/BookingScreen/Components/SelectionComponent/MainPage.scss';
import { HiOutlineSquares2X2, HiSquaresPlus } from 'react-icons/hi2';
import { getSession } from '../../../../Services/Others';
import Buttons from '../../../../Components/Forms/Buttons';
import { BiSkipNext, BiSkipPrevious } from 'react-icons/bi';
import { MdOutlineDisplaySettings } from "react-icons/md";


const BookingSelectionPage = (props) => {

  const AppId = getSession('AppId');
  const UserId = getSession('UserId');
  const CompId = getSession('CompId');
  const BranchId = getSession('BranchId');
  const UserType = getSession('UserType');
  const carouselRef = useRef();
  const childRef = useRef();
  const dispatch = useDispatch();
  const DefaultThemes = useSelector(GlobalDefaultTheme);
  const OthersTheme = useSelector(GlobalOthersTheme);
  // const [activeTheme, setActiveTheme] = useState(
  //   'default'
  // );
  const activeTheme = useSelector(GlobalActiveTheme)
  const SelectedTheme = useSelector(GlobalSelectedTheme)

  const mergedThemes = DefaultThemes.concat(OthersTheme)
  const [currentSlide, setCurrentSlide] = useState(0);
  console.log(SelectedTheme, "currentSlide")
  const [OthersCount, setOthersCount] = useState(1);
  const [isNext, isSetNext] = useState(true);
  const rightIsLastSlide = currentSlide === mergedThemes.length - 1;
  const leftIsFirstSlide = currentSlide === 0 && OthersCount > 1;
  const [pendingSlide, setPendingSlide] = useState(null);
  // useEffect(() => {
  //     if (DefaultThemes?.ThemeName!== null) {
  //       const index = DefaultThemes?.findIndex(
  //         (style) => style.name === DefaultThemes?.ThemeName);
  //       if (index !== -1) {
  //         setCurrentSlide(index);
  //         setSelectedStyleName(DefaultThemes[index].name);
  //         carouselRef?.current?.goTo(index);
  //       }
  //     }
  //   }, [DefaultThemes]);
  const previewData = props.hasOwnProperty('data')
    ? props['data']
    : useSelector(getPreviewData);
  console.log(previewData, 'previewDatapreviewData');
  useEffect(() => {
    GetOthersTemplate()
    // gettemplatedetail()
  }, [])
  const gettemplatedetail = async () => {
    let tempdetail = await dispatch(
      getTemplate({ CompId: CompId, BranchId: BranchId, AppId: AppId })
    ).unwrap();

    if (tempdetail?.data?.statusCode == 1) {
      dispatch(changeActiveTheme("customised"));
    }
  };

  const handleMainSubmit = () => {
    if (childRef.current) {
      childRef.current.submit(); // must match the method exposed in useImperativeHandle
    }
  };
  const renderPreviewLayout = () => {
    const layout = previewData?.BookingLayout?.[0];
    if (!layout) return <Skeleton active />;
    if (layout.includes('Combo')) return <ComboLayout1 data={previewData} />;
    switch (layout) {
      case 'Layout1':
        return <PreviewLayout1 data={previewData} />;
      case 'Layout2':
        return <PreviewLayout2 data={previewData} />;
      case 'Layout3':
        return <PreviewLayout3 data={previewData} />;
      case 'Layout4':
        return <PreViewLayout4 data={previewData} />;
      case 'Layout5':
        return <PreviewLayout5 data={previewData} />;
      case 'Layout6':
        return <PreViewLayout6 data={previewData} />;
      default:
        return <Skeleton active />;
    }
  };
  useEffect(() => {
    if (pendingSlide !== null) {
      const updatedThemes = DefaultThemes.concat(OthersTheme);
      if (pendingSlide < updatedThemes.length) {
        carouselRef.current.goTo(pendingSlide);
        setCurrentSlide(pendingSlide);
        let seltheme = updatedThemes[pendingSlide];
        dispatch(changeThemeCreation({ formtype: 'edit', editdata: seltheme }));
        dispatch(changeSelectedTheme({ ThemeId: seltheme?.TemplatePreferenceId, ThemeName: seltheme?.ThemeName }));
      }
      setPendingSlide(null); // Reset
    }
  }, [OthersTheme, DefaultThemes, pendingSlide, dispatch]);
  //  const leftOnclick = async () => {

  //     const newIndex = (currentSlide - 1 + mergedThemes.length) % mergedThemes.length;
  //     carouselRef.current.goTo(newIndex);
  //     setCurrentSlide(newIndex);
  //       let seltheme = mergedThemes[newIndex];
  //     console.log(seltheme, 'seltheme');
  //     dispatch(changeThemeCreation({ formtype: 'edit', editdata: seltheme }));
  //    dispatch(changeSelectedTheme({ThemeId:seltheme?.TemplatePreferenceId,ThemeName:seltheme?.ThemeName}));

  //     // let Styles = await dispatch(
  //     //   getConfigType({ TypeName: 'Print Style' })
  //     // ).unwrap();
  //     // if (Styles?.data?.statusCode === 1) {
  //     //   // setStyleData(Styles?.data?.data)
  //     //   let configData = Styles?.data?.data;
  //     //   let confilteredData = configData.filter(
  //     //     (item) => item.ConfigName == DefaultThemes[newIndex]?.name
  //     //   );
  //     //   handleParentAction(confilteredData?.[0]?.ConfigId, newIndex);
  //     //   console.log(confilteredData?.ConfigId);

  //       // handleStyle(configId)
  //     // }
  //   };
  // const RightOnclick = async () => {
  //   // let Allthemes = 
  //   // alert('Right Clicked');
  //   const newIndex = (currentSlide + 1) % mergedThemes.length;
  //   carouselRef.current.goTo(newIndex);
  //   setCurrentSlide(newIndex);
  //   let seltheme = mergedThemes[newIndex];
  //   console.log(seltheme, 'seltheme');
  //   dispatch(changeThemeCreation({ formtype: 'edit', editdata: seltheme }));
  //  dispatch(changeSelectedTheme({ThemeId:seltheme?.TemplatePreferenceId,ThemeName:seltheme?.ThemeName}));
  //   // console.log(newIndex,currentSlide, 'newIndexnewIndex');
  //     // handleParentAction(confilteredData?.[0]?.ConfigId, newIndex);

  //     // handleStyle(configId)

  // };
  const RightOnclick = async () => {
    if (rightIsLastSlide && isNext) {
      await GetMoreTemplate();
      setPendingSlide(currentSlide + 1); // Ask to jump to the next slide after fetch
    } else {
      const newIndex = (currentSlide + 1) % mergedThemes.length;
      carouselRef.current.goTo(newIndex);
      setCurrentSlide(newIndex);
      let seltheme = mergedThemes[newIndex];
      dispatch(changeThemeCreation({ formtype: 'edit', editdata: seltheme }));
      dispatch(changeSelectedTheme({ ThemeId: seltheme?.TemplatePreferenceId, ThemeName: seltheme?.ThemeName }));
    }
  };

  const leftOnclick = async () => {
    if (leftIsFirstSlide) {
      await GetLessTemplate();
      setPendingSlide(DefaultThemes.concat(OthersTheme).length - 1); // Ask to jump to last slide after fetch
    } else {
      const newIndex = (currentSlide - 1 + mergedThemes.length) % mergedThemes.length;
      carouselRef.current.goTo(newIndex);
      setCurrentSlide(newIndex);
      let seltheme = mergedThemes[newIndex];
      dispatch(changeThemeCreation({ formtype: 'edit', editdata: seltheme }));
      dispatch(changeSelectedTheme({ ThemeId: seltheme?.TemplatePreferenceId, ThemeName: seltheme?.ThemeName }));
    }
  };
  const CustomisedthemeSelection = async (seltheme) => {
    dispatch(changeActiveTheme(seltheme));
    if (seltheme == 'customised') {
      let themedtl = await dispatch(
        getTemplate({ CompId: CompId, BranchId: BranchId, AppId: AppId })
      ).unwrap();
      if (themedtl.data?.statusCode == 0) {
        // settemplateData({});
        dispatch(changeThemeCreation({ formtype: 'new' }));
      } else if (themedtl.data?.statusCode == 1) {
        // setTemptemplatedata(false);
      }
    } else {
      if (Object.keys(DefaultThemes)?.length > 0) {
        dispatch(changeSelectedTheme({ ThemeId: DefaultThemes?.[0]?.TemplatePreferenceId, ThemeName: DefaultThemes?.[0]?.ThemeName }));
        // settemplateData(DefaultThemes?.[0]);
        dispatch(changeThemeCreation({ formtype: 'edit', editdata: DefaultThemes?.[0] }));
      } else {
        dispatch(changeSelectedTheme({}));
        dispatch(changeThemeCreation({ formtype: 'new' }));

      }
    }
  }

  const handlesubmit = () => {
    const PostData = {};
    PostData['AppId'] = AppId;
    PostData['CompId'] = CompId;
    PostData['UserId'] = UserId;
    PostData['BranchId'] = BranchId;
    PostData['ColorId'] = colorFilteredArray;
    PostData['FontId'] = fontFilteredArray;
    PostData['CreatedBy'] = UserId;
  }
  const GetOthersTemplate = async () => {
    let OtherTemp = await dispatch(
      getOthersTemplate({ pagenumber: OthersCount })
    ).unwrap();
    if (OtherTemp?.data?.statusCode === 1) {
      let withname = OtherTemp.data?.data?.map((temp, index) => ({
        ...temp,
        ThemeName: `Theme ${index + 1 + OthersCount * 10 - 10}`,
      }));
      dispatch(changeOthersTheme(withname))
    } else {
    }
  };
  const GetMoreTemplate = async () => {
    setOthersCount(OthersCount + 1);
    let tempcount = OthersCount + 1;
    let OtherTemp1 = await dispatch(
      getOthersTemplate({ pagenumber: tempcount + 1 })
    ).unwrap();

    if (OtherTemp1?.data?.statusCode != 1) {
      isSetNext(false);
    }
    let OtherTemp = await dispatch(
      getOthersTemplate({ pagenumber: tempcount })
    ).unwrap();
    if (OtherTemp?.data?.statusCode === 1) {
      let withname = OtherTemp.data?.data?.map((temp, index) => ({
        ...temp,
        ThemeName: `Theme ${index + 1 + (tempcount - 1) * 10}`,
      }));
      dispatch(changeOthersTheme(withname))

    } else {
      setMessageType('warning');
      setMessageData('No more templates');
    }
  };
  const GetLessTemplate = async () => {
    setOthersCount(OthersCount - 1);
    let tempcount = OthersCount - 1;
    let OtherTemp = await dispatch(
      getOthersTemplate({ pagenumber: tempcount })
    ).unwrap();
    if (OtherTemp?.data?.statusCode === 1) {
      let withname = OtherTemp.data?.data?.map((temp, index) => ({
        ...temp,
        ThemeName: `Theme ${index + 1 + (tempcount - 1) * 10}`,
      }));
      dispatch(changeOthersTheme(withname))

      isSetNext(true);
    } else {
    }
  };
  const clearOtherTemplate = async () => {
    dispatch(changeOthersTheme([]))
    setOthersCount(1);
  };
  return (
    <div className='SalesSetupMaster'>

      <div className="Salessetup-header">
        <h1 className="formHeader">
          <p> <MdOutlineDisplaySettings size={30} color='#2563eb' /> Sales Setup</p>
          <div>Customize your sales screen here </div>
        </h1>
        <div className="defaultandCustomisedThemeSales">
          <div
            className={activeTheme === 'default' ? 'selected' : ''}
            onClick={() => CustomisedthemeSelection('default')}
          >
            <HiOutlineSquares2X2 size={16} />
            Default Theme
          </div>
          <div
            className={activeTheme === 'customised' ? 'selected' : ''}
            onClick={() => CustomisedthemeSelection('customised')}
          >
            <HiSquaresPlus size={16} /> Customized Theme
          </div>

        </div>

        {activeTheme === 'default' &&
          <div className="Default-SubmitButton">
            <Buttons
              buttonText="Save"
              color="901D77"
              handleSubmit={handleMainSubmit}
              icon={<ArrowRightOutlined />}
            />
          </div>
        }
      </div>
      <div className='salesScreenView'
      >
        {activeTheme === 'default' ?
          <>
            <div
              className="default-Sales-dotted-box"
            >

              <Button
                icon={<LeftOutlined />}
                onClick={() => leftOnclick()}
                style={{
                  position: 'absolute',
                  top: '42%',
                  left: '15%',
                  zIndex: 2,
                  width: '40px',
                  height: '40px',
                  fontWeight: 'bold',
                  borderRadius: '50%',
                  boxShadow: '0 2px 8px rgba(0, 0, 0, 0.15)',
                }}
              />
              <Button
                icon={<RightOutlined />}
                onClick={() => RightOnclick()}
                style={{
                  position: 'absolute',
                  top: '42%',
                  right: '13%',
                  zIndex: 2,
                  width: '40px',
                  height: '40px',
                  fontWeight: 'bold',
                  borderRadius: '50%',
                  boxShadow: '0 2px 8px rgba(0, 0, 0, 0.15)',
                }}
              />
              <Carousel
                ref={carouselRef}
                dots={false}
                draggable={true}
                style={{ width: '100%', height: '100%', position: 'relative' }}
              // afterChange={handleCarouselChange}
              >
                {Object.keys(previewData)?.length > 0 ? (
                  renderPreviewLayout()
                ) : (
                  <div>
                    <Skeleton active />
                  </div>
                )}
              </Carousel>

            </div>

            <div style={{ display: 'none' }}>
              <SelectionComponent ref={childRef} />
            </div>
          </>
          :
          <>
            <div
              className="Sales-dotted-box"
              style={{ width: '55%', height: '85%', position: 'relative' }}
            >

              <Carousel
                ref={carouselRef}
                dots={false}
                draggable={true}
                style={{ width: '100%', height: '100%', position: 'relative' }}
              // afterChange={handleCarouselChange}
              >
                {Object.keys(previewData)?.length > 0 ? (
                  renderPreviewLayout()
                ) : (
                  <div>
                    <Skeleton active />
                  </div>
                )}
              </Carousel>
            </div>
            <div className='SelectionComponentImport'>
              <SelectionComponent ref={childRef} />
            </div>
          </>
        }
      </div>

    </div>
  );
};


export default BookingSelectionPage;
