import React, { useState, useEffect } from 'react';
import { useDispatch, useSelector } from 'react-redux';
import { Badge } from 'antd';
import {
  changealldata,
  GlobalAllItemData,
  ChangeAllItemData,
  PostFavItemsData,
  getEditFavItems,
  ChangeAutoLocatetofav,
  getSelectedFavItems,
} from '../../../../Features/BookingScreen/BookingData/BookingData.js';
import {
  changepreOrder,
  GlobalpreOrderOpen,
} from '../../../../Features/BookingScreen/PreOrder/PreOrder.js';
import Buttons from '../../../../Components/Forms/Buttons.jsx';
import { getSession } from '../../../../Services/Others.js';
import {
  HeartFilled,
  CloseCircleFilled,
  ArrowRightOutlined,
} from '@ant-design/icons';
import PozoFavIcon from './Pozo retail icons/PozoFavIcon.jsx';
import { SlArrowDown } from 'react-icons/sl';
import { IoCloseSharp } from 'react-icons/io5';
import TooltipWrapper from '../../../../Components/Tooltip/Tooltip';
import { isMobile } from 'react-device-detect';
import '../../../../Styles/BookingScreen/Components/BSNavbar/BSNavbar2.scss';

const BSNavBarFavItems = ({ type, fill, drawerOpen = false }) => {
  const [open, setOpen] = useState(false);
  const [favopen, setFavopen] = useState(false);
  const globalAllItemdata = useSelector(GlobalAllItemData);
  const preOrderOpen = useSelector(GlobalpreOrderOpen);
  const [RemovedData, setRemovedData] = useState([]);
  const [searchQuery, setSearchQuery] = useState('');
  const [autoLocatetofav, setautoLocatetofav] = useState(false);
  const [filteredItems, setFilteredItems] = useState(globalAllItemdata);
  const CompId = getSession('CompId');
  const BranchId = getSession('BranchId');
  const AppId = getSession('AppId');
  const UserId = getSession('UserId');
  const dispatch = useDispatch();
  useEffect(() => {
    setFilteredItems(globalAllItemdata);
  }, [globalAllItemdata]);

  const fetchEditFavItems = async () => {
    let data = {
      CompId: CompId,
      BranchId: BranchId,
      AppId: AppId,
    };
    await dispatch(getEditFavItems(data)).unwrap();
  };

  useEffect(() => {
    fetchEditFavItems();
  }, []);

  const AddFav = async () => {
    setautoLocatetofav(true);
    setFavopen(true);
    if (type !== 'small-screen') {
      fetchEditFavItems();
    }
    if (open == false) {
      if (preOrderOpen) {
        await dispatch(changepreOrder(false));
      }
      setOpen(true);
    } else {
      if (type !== 'small-screen') {
        setOpen(false);
      }
    }
    await dispatch(ChangeAutoLocatetofav(autoLocatetofav));
  };

  useEffect(() => {
    if (drawerOpen) {
      AddFav();
    } else {
      setOpen(false);
    }
  }, [drawerOpen]);

  useEffect(() => {
    if (preOrderOpen) {
      setOpen(false);
    }
  }, [preOrderOpen]);

  useEffect(() => {
    DisData();
  }, [open]);

  useEffect(() => {
    DisItemData();
  }, [RemovedData]);

  const DisData = async () => {
    await dispatch(changealldata(open));
  };

  const DisItemData = async () => {
    await dispatch(ChangeAllItemData(RemovedData));
  };

  const RemoveData = (item) => {
    // const ss = globalAllItemdata?.filter((e) => e.ProdName !== item.ProdName);
    const ss = globalAllItemdata?.filter(
      (e) => !(e.ProdName == item.ProdName && e.ProdCat == item.ProdCat)
    );
    setRemovedData(ss);
  };

  const PostFavitemData = async () => {
    setautoLocatetofav(false);
    locatetofav();
    let data1 = [];
    filteredItems?.map((item) =>
      data1.push({
        ProdId: item.ProdId,
        ProdCat: item.ProdCat,
      })
    );

    let data = {
      CompId: CompId,
      BranchId: BranchId,
      AppId: AppId,
      CreatedBy: UserId,
      ItemDetails: data1,
    };
    let res = await dispatch(PostFavItemsData(data)).unwrap();
    if (res?.data?.statusCode === 1) {
      dispatch(getSelectedFavItems(data)).unwrap();
    }
    setOpen(false);
    await dispatch(ChangeAutoLocatetofav(autoLocatetofav));
  };

  const locatetofav = async () => {
    await dispatch(ChangeAutoLocatetofav(autoLocatetofav));
  };
  const handleSearch = (e) => {
    const query = e.target.value;
    setSearchQuery(query);

    // Filter items based on the search query
    const filteredData = globalAllItemdata?.filter((item) =>
      item.ProdName?.toLowerCase()?.includes(query?.toLowerCase())
    );
    setFilteredItems(filteredData);
  };
  const handleClose = () => {
    setOpen(false);
    fetchEditFavItems();
  };

  return (
    <>
      <div style={preOrderOpen ? { pointerEvents: 'none' } : {}}>
        <TooltipWrapper title={'Favourites'} isMobile={isMobile}>
          <Badge
            count={globalAllItemdata?.length}
            offset={[-5, 10]}
            size="small"
          >
            <PozoFavIcon
              className="BSBillingNav-icon"
              onClick={(e) => {
                e.stopPropagation(); // 👈 prevents parent click
                AddFav();
              }}
              fill={
                globalAllItemdata?.length > 0
                  ? '#52C41A'
                  : fill
                    ? fill
                    : '#6b7280'
              }
              style={{
                cursor: 'pointer',
                color: globalAllItemdata ? '#52C41A' : 'default',
              }}
            />
          </Badge>
        </TooltipWrapper>
      </div>

      {open && favopen && (
        <div className="AddFavList">
          <div className="AddFavList-subContainer">
            <div
              style={{
                display: 'flex',
                justifyContent: 'space-between',
                fontFamily: 'gilroy',
                padding: '1rem 0',
                alignItems: 'center',
                width: '100%',
              }}
            >
              <h3>
                {' '}
                <HeartFilled style={{ color: '#FF4D4F' }} /> Favourites{' '}
              </h3>
              <div
                style={{
                  display: 'flex',
                  justifyContent: 'space-between',
                  gap: '1rem',
                }}
              >
                <SlArrowDown
                  className="fav-Downarrow"
                  onClick={() => setFavopen(false)}
                />
                <IoCloseSharp
                  className="fav-close"
                  onClick={() => handleClose()}
                  style={{
                    display: 'flex',
                    color: '#ff0000',
                    fontSize: '20px',
                    cursor: 'pointer',
                  }}
                />
                {/* <button className="fav-close" onClick={() => handleClose ()}>close</button> */}
              </div>
            </div>

            <input
              className="favItem-SearchBar"
              type="search"
              placeholder="Search"
              style={{ padding: '0 0 0 1rem' }}
              value={searchQuery}
              onChange={handleSearch}
            />
          </div>

          <div className="AddFavItemListCont">
            {filteredItems?.map((item, index) => (
              <div className="AddFavItemList" key={index}>
                {/* <p>{item.ProdName}</p> */}
                {console.log('item', item)}
                <p>
                  {item.ProdName} {`( ${item.ProdCatName})`}{' '}
                </p>
                <CloseCircleFilled
                  style={{ color: '#FF4D4F' }}
                  onClick={() => RemoveData(item)}
                />
              </div>
            ))}
          </div>

          <div className="favsbmtbtn">
            <Buttons
              buttonText="SUBMIT"
              color="901D77"
              icon={<ArrowRightOutlined />}
              handleSubmit={PostFavitemData}
            ></Buttons>
          </div>
        </div>
      )}
    </>
  );
};
export default BSNavBarFavItems;
