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';
import Toast from '@components/Shared/Toast/Index';

const data = [
  ['*', 'A1', 'A2', 'A3', '*', 'A4', 'A5', 'A6', '*'],
  ['B1', 'B2', 'B3', 'B4', '*', 'B5', 'B6', 'B7', 'B8'],
  ['C1', 'C2', 'C3', 'C4', '*', 'C5', 'C6', 'C7', 'C8'],
  ['D1', 'D2', 'D3', 'D4', '*', 'D5', 'D6', 'D7', 'D8'],
  ['E1', 'E2', 'E3', 'E4', '*', 'E5', 'E6', 'E7', 'E8'],
  ['F1', 'F2', 'F3', 'F4', '*', 'F5', 'F6', 'F7', 'F8'],
  ['G1', 'G2', 'G3', 'G4', '*', 'G5', 'G6', 'G7', 'G8'],
  ['*', 'H1', 'H2', 'H3', '*', 'H4', 'H5', 'H6', '*']
];

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);
  const [toast, setToast] = useState(null);

  useEffect(() => {
    const initializeSeatsData = async () => {
      await fetchSelectedSeats();
      setShowSeatsModal(getItem(appConstants.MODAL));
    };
    initializeSeatsData();
  }, []);

  const fetchSelectedSeats = async () => {
    try {
      const data = await getSelectedSeatsApi();
      const currentData = data?.find((e) => e.userid == userId);
      if (currentData?.selected?.length > 0) {
        setItem('modal', false);
      } else {
        setItem('modal', true);
      }

      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] : [];
        showToast('Seat Count Exeeded', 'info');
      }
      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);
  };

  const showToast = (message, type = 'info') => {
    setToast({ message, type });
    setTimeout(() => setToast(null), 3000);
  };

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

      {toast && (
        <Toast
          message={toast.message}
          type={toast.type}
          onClose={() => setToast(null)}
        />
      )}
    </>
  );
};

export default BookingPage;
