import { useEffect, useState } from 'react';
import { useNavigate } from 'react-router-dom';
import { getItem, reset, setItem } from '../../lib/localStorage';
import { appConstants } from '../../lib/AppConstants';
import {
  getSelectedSeatsApi,
  editSeatsApi,
  createSeatApi,
  saveSeatSelectionCountApi,
  getSeatSelectionCountApi
} from '../../lib/api';
import BookingWrapper from '../../components/Layout/BookingWrapper/Index';
import Header from '../../components/Layout/Header/Index';
import Modal from '../../components/Shared/Modal/Index';
import ConfirmSeatContent from '../../components/TopLevel/ConfirmSeatContent/Index';
import SeatSelectionContent from '../../components/TopLevel/SeatSelectionContent/Index';
import Button from '../../components/Base/Button/Index';
import LegendWrapper from '../../components/TopLevel/LegendWrapper/Index';
import img from '../../assets/images/power-button_12080802.png';
import styles from './styles.module.css';

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);
  useEffect(() => {
    const fetchSeatSelectionCount = async () => {
      const data = await getSeatSelectionCountApi(userId);
      setNoOfSeats(data?.selectionCount);
    };
    fetchSelectedSeats();
    fetchSeatSelectionCount();
    setShowSeatsModal(getItem(appConstants.MODAL));
  }, []);

  const fetchSelectedSeats = async () => {
    const data = await getSelectedSeatsApi();
    const currentData = data?.find((e) => e.userid == userId);
    setSelectedSeats(data);
    setCurrentSeats(currentData?.selected);
  };

  const data = [
    {
      row_id: 1,
      columnData: [
        {
          id: 0,
          status: 'aisle'
        },
        {
          id: 1
        },
        {
          id: 2
        },
        {
          id: 3
        },
        {
          id: 0
        },
        {
          id: 4
        },

        {
          id: 5
        },
        {
          id: 6
        },
        {
          id: 0,
          status: 'aisle'
        }
      ]
    },
    {
      row_id: 2,
      columnData: [
        {
          id: 1,
          status: 'available'
        },
        {
          id: 2,
          status: 'available'
        },
        {
          id: 3,
          status: 'available'
        },
        {
          id: 4,
          status: 'available'
        },
        {
          id: 0,
          status: 'aisle'
        },
        {
          id: 5,
          status: 'available'
        },

        {
          id: 6,
          status: 'available'
        },
        {
          id: 7,
          status: 'available'
        },
        {
          id: 8,
          status: 'available'
        }
      ]
    },
    {
      row_id: 3,
      columnData: [
        {
          id: 1
        },
        {
          id: 2
        },
        {
          id: 3
        },
        {
          id: 4
        },
        {
          id: 0
        },
        {
          id: 5
        },

        {
          id: 6
        },
        {
          id: 7
        },
        {
          id: 8
        }
      ]
    },
    {
      row_id: 4,
      columnData: [
        {
          id: 1
        },
        {
          id: 2
        },
        {
          id: 3
        },
        {
          id: 4
        },
        {
          id: 0
        },
        {
          id: 5
        },

        {
          id: 6
        },
        {
          id: 7
        },
        {
          id: 8
        }
      ]
    },
    {
      row_id: 5,
      columnData: [
        {
          id: 1
        },
        {
          id: 2
        },
        {
          id: 3
        },
        {
          id: 4
        },
        {
          id: 0
        },
        {
          id: 5
        },

        {
          id: 6
        },
        {
          id: 7
        },
        {
          id: 8
        }
      ]
    },
    {
      row_id: 6,
      columnData: [
        {
          id: 1
        },
        {
          id: 2
        },
        {
          id: 3
        },
        {
          id: 4
        },
        {
          id: 0
        },
        {
          id: 5
        },

        {
          id: 6
        },
        {
          id: 7
        },
        {
          id: 8
        }
      ]
    },
    {
      row_id: 7,
      columnData: [
        {
          id: 1
        },
        {
          id: 2
        },
        {
          id: 3
        },
        {
          id: 4
        },
        {
          id: 0
        },
        {
          id: 5
        },

        {
          id: 6
        },
        {
          id: 7
        },
        {
          id: 8
        }
      ]
    },
    {
      row_id: 8,
      columnData: [
        {
          id: 0,
          status: 'aisle'
        },
        {
          id: 1
        },
        {
          id: 2
        },
        {
          id: 3
        },
        {
          id: 0
        },
        {
          id: 4
        },

        {
          id: 5
        },
        {
          id: 6
        },
        {
          id: 0,
          status: 'aisle'
        }
      ]
    }
  ];

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

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

  const modalClose = () => {
    setItem('modal', false);
    if (userId && noOfSeats) {
      saveSeatSelectionCountApi(userId, noOfSeats);
    }
    fetchSelectedSeats();
    setShowSeatsModal(false);
  };

  const finalCancel = () => {
    const current = selectedSeats?.find((ele) => ele.userid == userId);
    const mergedSeats = [
      ...currentSeats.filter(
        (cs) =>
          !current?.selected.some(
            (ss) => ss.row === cs.row && ss.seat === cs.seat
          )
      ),
      ...current?.selected.filter(
        (ss) =>
          !currentSeats.some((cs) => cs.row === ss.row && cs.seat === ss.seat)
      )
    ];

    setCurrentSeats(mergedSeats);
    setShowSeatsConfirmationModal(false);
  };

  const onSelectSeats = (rowId, columnId) => {
    setCurrentSeats((prev) => {
      const found = prev?.find((e) => e.row === rowId && e.seat === columnId);
      let updatedSeats;

      if (found) {
        updatedSeats = prev?.filter(
          (e) => !(e.row === rowId && e.seat === columnId)
        );
        if (updatedSeats?.length === parseInt(noOfSeats)) {
          setButtonState(false);
        } else {
          setButtonState(true);
        }
      } else {
        console.log('INSIDE ELSE', prev?.length, noOfSeats);
        if (prev?.length < noOfSeats || !prev?.length) {
          console.log('INSIDE IF 22');
          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 {
          console.log('INSIDE ELSE 222');

          updatedSeats = prev ? [...prev] : [];
        }
      }

      return updatedSeats;
    });
  };

  const onSeatsConfirm = () => {
    setCurrentSeats([...currentSeats]);
    setShowSeatsConfirmationModal(true);
  };

  const seatsFinal = async () => {
    const existingUserSeatMap = selectedSeats?.find((ele) => ele.id == userId);
    const fetchData = async () => {
      let data = await getSelectedSeatsApi();
      setSelectedSeats(data);
    };
    if (existingUserSeatMap) {
      await editSeatsApi(userId, currentSeats);
    } else {
      let info = {
        id: userId,
        userid: userId,
        selected: currentSeats
      };
      await createSeatApi(info);
    }
    fetchData();
    setShowSeatsConfirmationModal(false);
  };

  return (
    <div className={styles['seat-booking-wrapper']}>
      <img
        src={img}
        className={styles['logout']}
        width={30}
        onClick={() => logout()}
      />
      <div className={styles['screen-wrapper']}>
        <Header>Choose Seats</Header>
        <BookingWrapper
          seatData={data}
          selectedSeats={selectedSeats}
          onSeatClick={onSelectSeats}
          currentSeats={currentSeats}
        />
      </div>
      <div className={styles['btn-wrapper']}>
        <Button size={'lg'} onClick={onSeatsConfirm} disabled={buttonState}>
          Confirm
        </Button>
      </div>
      <LegendWrapper />
      {showSeatsModal && (
        <Modal>
          <SeatSelectionContent
            onChange={onModalChange}
            onConfirm={modalClose}
            disabled={modalButtonState}
          />
        </Modal>
      )}
      {showSeatsConfirmationModal && (
        <Modal>
          <ConfirmSeatContent onConfirm={seatsFinal} />
        </Modal>
      )}
    </div>
  );
};

export default BookingPage;
