import { useEffect, useState } from 'react';
import { useNavigate } from 'react-router-dom';

import BookingWrapper from '@components/Layout/BookingWrapper/Index';
import Header from '@components/Layout/Header/Index';
import ConfirmSeatContent from '@components/TopLevel/ConfirmSeatContent/Index';
import SeatSelectionContent from '@components/TopLevel/SeatSelectionContent/Index';
import SuccessModal from '@components/TopLevel/SuccessModal/Index';
import LegendWrapper from '@components/TopLevel/LegendWrapper/Index';
import LogoutButton from '@components/Shared/LogoutButton/Index';

import { getItem, reset, setItem } from '../../lib/sessionStorage';
import { appConstants } from '../../lib/AppConstants';
import {
  getSelectedSeatsApi,
  editSeatsApi,
  createSeatApi
} from '../../lib/api';

const data = [
  ['*', 1, 2, 3, '*', 4, 5, 6, '*'],
  [1, 2, 3, 4, '*', 5, 6, 7, 8],
  [1, 2, 3, 4, '*', 5, 6, 7, 8],
  [1, 2, 3, 4, '*', 5, 6, 7, 8],
  [1, 2, 3, 4, '*', 5, 6, 7, 8],
  [1, 2, 3, 4, '*', 5, 6, 7, 8],
  [1, 2, 3, 4, '*', 5, 6, 7, 8],
  ['*', 1, 2, 3, '*', 4, 5, 6, '*']
];

const BookingPage = () => {
  let userId = getItem(appConstants.USER);
  const navigate = useNavigate();

  const [selectedSeats, setSelectedSeats] = useState(); //persisted seats state
  const [currentSeats, setCurrentSeats] = useState([]); // currently selecting seats before booking(local)
  const [showSeatsModal, setShowSeatsModal] = useState(
    getItem(appConstants.MODAL)
  );
  const [showSeatsConfirmationModal, setShowSeatsConfirmationModal] =
    useState(false);
  const [noOfSeats, setNoOfSeats] = useState();
  const [buttonState, setButtonState] = useState(true);
  const [modalButtonState, setModalButtonState] = useState(true);
  const [showSuccessModal, setShowSuccessModal] = useState(false);
  useEffect(() => {
    fetchSelectedSeats();
    setShowSeatsModal(getItem(appConstants.MODAL));
  }, []);

  const fetchSelectedSeats = async () => {
    try {
      const data = await getSelectedSeatsApi();
      const currentData = data?.find((e) => e.userid == userId);
      const structuredData = data.flatMap((user) => user.selected);

      const temp = structuredData?.filter(
        (e) =>
          !currentData?.selected?.some(
            (e2) => e2.row === e.row && e2.seat === e.seat
          )
      );

      setSelectedSeats(temp);
      setCurrentSeats(currentData?.selected);
      setNoOfSeats(
        currentData?.selected?.length
          ? currentData?.selected?.length
          : noOfSeats
      );
    } catch (error) {
      console.error('Error in fetchSelectedSeats:', error);
      setSelectedSeats([]);
      setCurrentSeats([]);
      setNoOfSeats(noOfSeats);
    }
  };

  const logout = () => {
    reset();
    navigate('/login');
  };

  const onModalChange = (value) => {
    const numericValue = parseInt(value, 10);
    setNoOfSeats(numericValue);
    if (value && value !== '') {
      setModalButtonState(false);
    } else {
      setModalButtonState(true);
    }
  };

  const handleSeatSelectionConfirm = () => {
    setItem('modal', false);
    fetchSelectedSeats();
    setShowSeatsModal(false);
  };

  const handleModalCancel = () => {
    setShowSeatsConfirmationModal(false);
  };

  const handleSeatRemove = (rowId, columnId) => {
    setCurrentSeats((prev) => {
      let updatedSeats;
      updatedSeats = prev?.filter(
        (e) => !(e.row === rowId && e.seat === columnId)
      );
      if (updatedSeats?.length === parseInt(noOfSeats)) {
        setButtonState(false);
      } else {
        setButtonState(true);
      }
      return updatedSeats;
    });
  };

  const handleSeatAdd = (rowId, columnId) => {
    setCurrentSeats((prev) => {
      let updatedSeats;
      if (prev?.length < noOfSeats || !prev?.length) {
        if (prev) {
          updatedSeats = [...prev, { row: rowId, seat: columnId }];
        } else {
          updatedSeats = [{ row: rowId, seat: columnId }];
        }
        if (updatedSeats?.length === parseInt(noOfSeats)) {
          setButtonState(false);
        } else {
          setButtonState(true);
        }
      } else {
        updatedSeats = prev ? [...prev] : [];
      }
      return updatedSeats;
    });
  };

  const handleSeatsConfirm = () => {
    setShowSeatsConfirmationModal(true);
  };

  const handleSeatBooking = async () => {
    try {
      const data = await getSelectedSeatsApi();
      const existingUserSeatMap = data?.find((ele) => ele.id == userId);
      if (existingUserSeatMap) {
        await editSeatsApi(userId, currentSeats);
      } else {
        const info = {
          id: userId,
          userid: userId,
          selected: currentSeats
        };
        await createSeatApi(info);
      }
      setShowSeatsConfirmationModal(false);
      fetchSelectedSeats();
      setShowSuccessModal(true);
    } catch (error) {
      console.error('Error in seatsFinal:', error);
    }
  };

  const handleSuccessModalConfirm = () => {
    setShowSuccessModal(false);
    setButtonState(true);
  };

  return (
    <>
      <LogoutButton onLogout={logout} />
      <Header>Choose Seats</Header>
      <BookingWrapper
        seatData={data}
        selectedSeats={selectedSeats}
        currentSeats={currentSeats}
        onSeatRemove={handleSeatRemove}
        onSeatAdd={handleSeatAdd}
        onSeatsConfirm={handleSeatsConfirm}
        buttonState={buttonState}
      />
      <LegendWrapper />
      {showSeatsModal && (
        <SeatSelectionContent
          onChange={onModalChange}
          onConfirm={handleSeatSelectionConfirm}
          disabled={modalButtonState}
        />
      )}
      {showSeatsConfirmationModal && (
        <ConfirmSeatContent
          onConfirm={handleSeatBooking}
          onCancel={handleModalCancel}
        />
      )}
      {showSuccessModal && (
        <SuccessModal onConfirm={handleSuccessModalConfirm} />
      )}
    </>
  );
};

export default BookingPage;
