import { useCallback, useEffect, useState } from 'react';
import { useDispatch, useSelector } from 'react-redux';
import './IndividualBooking.scss';
import Compass from '../Tablebooking/Compass';
import {
  changeSelectChair,
  changeSelectTable,
  GlobalSelectedChair,
  GlobalSelectedTable,
} from '../../Features/BookingScreen/BookingData/BookingData';
import { getTableDtlsForSelfBooking } from '../../Features/TableBooking/TableBooking';
import {
  decryptToObject,
  extractLastNumber,
  getSession,
  sessionStore,
} from '../../Services/Others';
import Buttons from '../../Components/Forms/Buttons';
import { ArrowRightOutlined, ArrowLeftOutlined } from '@ant-design/icons';
import { useLocation, useNavigate } from 'react-router-dom';
import { getBranchDetail } from '../../Features/BrachLogin/BranchLogin';
import { IoIosArrowBack } from 'react-icons/io';

const subDirectory = import.meta.env.BASE_URL;

const IndividualBooking = () => {
  const dispatch = useDispatch();
  const navigate = useNavigate();
  const AppId = getSession('AppId');
  const CompId = getSession('CompId');
  const BranchId = getSession('BranchId');
  const tableCode = sessionStorage.getItem('SelfBookingId');

  const location = useLocation();
  const tableInfo = decryptToObject(getSession('bookInfo'));
  const selectedChairRedux = useSelector(GlobalSelectedChair);
  const selectedTableRedux = useSelector(GlobalSelectedTable);
  const dineInTypeId = getSession('table');
  const [tableData, setTableData] = useState([]);
  const [selectedChairs, setSelectedChairs] = useState(
    selectedChairRedux?.length > 0 ? selectedChairRedux : []
  );

  const [selectedTables, setSelectedTables] = useState(
    selectedTableRedux || []
  );

  useEffect(() => {
    if (tableInfo?.TableId) {
      fetchTableData();
    }
  }, [tableInfo?.TableId]);

  useEffect(() => {
    console.log(selectedChairs, 'selectedChairs');
  }, [selectedChairs]);

  useEffect(() => {
    if (
      (AppId === null || AppId === undefined) &&
      (CompId === null || CompId === undefined) &&
      (BranchId === null || BranchId === undefined)
    ) {
      fetchBranchData();
    }
  }, []);

  const fetchBranchData = async () => {
    const response = await dispatch(
      getBranchDetail({ BrId: BranchId })
    ).unwrap();
  };

  const fetchTableData = async () => {
    const res = await dispatch(
      getTableDtlsForSelfBooking({
        tableId: tableInfo.TableId,
        AppId,
        CompId,
        BranchId,
      })
    ).unwrap();
    if (res?.data?.statusCode === 1) {
      setTableData(res.data.data);
    }
  };

  const handleTableToggle = async (checked, tableId, chairDetails) => {
    const chairIds = chairDetails.map((c) => c.ChairId);

    if (checked) {
      const newChairs = chairIds.filter((id) => !selectedChairs.includes(id));
      const updatedChairs = [...selectedChairs, ...newChairs];
      const updatedTables = [...selectedTables, tableId];

      setSelectedChairs(updatedChairs);
      setSelectedTables(updatedTables);

      await dispatch(changeSelectChair(updatedChairs));
      await dispatch(changeSelectTable(updatedTables));
    } else {
      const updatedChairs = selectedChairs.filter(
        (id) => !chairIds.includes(id)
      );
      const updatedTables = selectedTables.filter((id) => id !== tableId);

      setSelectedChairs(updatedChairs);
      setSelectedTables(updatedTables);

      await dispatch(changeSelectChair(updatedChairs));
      await dispatch(changeSelectTable(updatedTables));
    }
  };

  const handleChairToggle = async (checked, chairId, chairDetails, tableId) => {
    const updatedChairs = checked
      ? [...selectedChairs, chairId]
      : selectedChairs.filter((id) => id !== chairId);

    setSelectedChairs(updatedChairs);
    await dispatch(changeSelectChair(updatedChairs));

    const allChairIds = chairDetails.map((c) => c.ChairId);
    const selectedForTable = allChairIds.every((id) =>
      updatedChairs.includes(id)
    );

    const updatedTables = selectedForTable
      ? [...new Set([...selectedTables, tableId])]
      : selectedTables.filter((id) => id !== tableId);

    setSelectedTables(updatedTables);
    await dispatch(changeSelectTable(updatedTables));
  };

  const handleBookingNavigate = () => {
    sessionStore('table', selectedChairs);
    navigate(`${subDirectory}kioskSelfBooking`, {
      state: { from: location.pathname },
    });
  };

  const renderChair = (chair, index, chairDetails, tableId) => {
    const isSelected = selectedChairs.includes(chair.ChairId);
    const isOccupied = chair.SalesStatus === 'Y';
    // const isOccupied = chair.OrderDetails?.length > 0;

    return (
      <div
        key={chair.ChairId}
        className={`modern-chair ${isSelected ? 'selected' : ''} ${isOccupied ? 'occupied' : 'available'}`}
      >
        <label className="chair-label">
          <input
            type="checkbox"
            value={chair.ChairId}
            onChange={
              !isOccupied
                ? (e) =>
                    handleChairToggle(
                      e.target.checked,
                      chair.ChairId,
                      chairDetails,
                      tableId
                    )
                : () => {}
            }
            checked={isSelected}
            style={{ display: 'none' }}
          />
          <span className="chair-content">{index + 1}</span>
        </label>
      </div>
    );
  };

  return (
    <div className="tablebooking-tables">
      <div className="self-booking-header">
        <div className="tb-choosetable">
          <div
            style={{ display: 'flex', alignItems: 'center', gap: '6px' }}
            onClick={() => navigate(`${subDirectory}selfBooking/${tableCode}`)}
          >
            <IoIosArrowBack className="back-button" /> Choose Chair
          </div>
        </div>
        <div className="table-status">
          <div className="table-status-div">
            <span className="avl" /> Available
          </div>
          <div className="table-status-div">
            <span className="sel" /> Booked
          </div>
          <div className="table-status-div">
            <span className="occ" /> Occupied
          </div>
          <div className="table-status-div">
            <span className="reserve" /> Reserved
          </div>
          <div className="table-status-div">
            <span className="selection" /> Selected
          </div>
        </div>
      </div>

      {tableData.map((table) => {
        const chairCount = table.ChairLevelSerDetails?.length || 0;
        const topChairs = Math.ceil(chairCount / 2);
        const dineInTypeId = tableData?.[0]?.DineInType;
        const hasOrders = table.ChairLevelSerDetails?.some(
          (c) => c.SalesStatus=="Y"
        );
    console.log(tableData,'tableData')
        return (
          <div key={table.TableId} className="modern-table-container">
            <div className="modern-expanded-table">
              <div className="expanded-table-header">
                <div className="table-selection">
                  {!hasOrders && (
                    <input
                      type="checkbox"
                      checked={selectedTables.includes(table.TableId)}
                      onChange={(e) =>
                        handleTableToggle(
                          e.target.checked,
                          table.TableId,
                          table.ChairLevelSerDetails
                        )
                      }
                    />
                  )}
                </div>
                <div className="table-info">
                  <h3 className="expanded-table-name">
                    {table.TableName}
                    {/* {table.TableName} - {extractLastNumber(table.TableId)} */}
                  </h3>
                </div>
              </div>

              <div className="horizontal-table-layout">
                <div className="chairs-row top-chairs">
                  {table.ChairLevelSerDetails?.slice(0, topChairs).map(
                    (chair, idx) =>
                      renderChair(
                        chair,
                        idx,
                        table.ChairLevelSerDetails,
                        table.TableId,
                        dineInTypeId
                      )
                  )}
                </div>

                <div className="central-table">
                  <div className="table-surface">
                    {/* <span className="table-label">{table.TableName}</span> */}
                    <div>
                      <Compass tableName={table.TableName} />
                    </div>
                  </div>
                </div>

                <div className="chairs-row bottom-chairs">
                  {table.ChairLevelSerDetails?.slice(topChairs).map(
                    (chair, idx) =>
                      renderChair(
                        chair,
                        topChairs + idx,
                        table.ChairLevelSerDetails,
                        table.TableId,
                        dineInTypeId
                      )
                  )}
                </div>
              </div>
            </div>
            <div className="chair-submit" onClick={handleBookingNavigate}>
              <Buttons
                buttonText="ORDER NOW"
                color="901D77"
                icon={<ArrowRightOutlined />}
                disabled={selectedChairs?.length === 0}
              />
            </div>
          </div>
        );
      })}
    </div>
  );
};

export default IndividualBooking;
