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 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();

  useEffect(() => {
    const fetchSelectedSeats = async () => {
      const data = await getSelectedSeatsApi();
      const currentData = data.find((e) => e.userid == userId);
      setSelectedSeats(data);
      setCurrentSeats(currentData.selected);
    };
    const fetchSeatSelectionCount = async () => {
      const data = await getSeatSelectionCountApi(userId);
      setNoOfSeats(data?.selectionCount);
    };
    fetchSelectedSeats();
    fetchSeatSelectionCount();
    setShowSeatsModal(getItem(appConstants.MODAL));
  }, []);

  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) => {
    setNoOfSeats(value);
  };

  const modalClose = () => {
    setItem('modal', false);
    if (userId && noOfSeats) {
      saveSeatSelectionCountApi(userId, noOfSeats);
    }
    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) => {
    const currentData = data.find((e) => e.userid == userId);
    const currentSelected = currentData.selected;
    let totalAllowedCount = currentSelected.length + currentSeats.length;
    setCurrentSeats((prev) => {
      const found = prev.find((e) => e.row == rowId && e.seat == columnId);
      if (found) {
        return currentSeats.filter(
          (e) => !(e.row == rowId && e.seat == columnId)
        );
      } else {
        if (totalAllowedCount < noOfSeats) {
          if (currentSeats.length < noOfSeats) {
            let obj = {
              row: rowId,
              seat: columnId
            };
            return [...prev, obj];
          } else {
            return [...prev];
          }
        }
      }
    });
  };

  const onSeatsConfirm = () => {
    const current = selectedSeats?.find((ele) => ele.userid == userId);

    const found = current?.selected.some((e) =>
      currentSeats.some((e2) => e2.row == e.row && e2.seat == e.seat)
    );

    if (found) {
      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);
    } else {
      if (current) {
        setCurrentSeats([...currentSeats, ...current.selected]);
      } else {
        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);
    }
    setCurrentSeats([]);
    fetchData();
    setShowSeatsConfirmationModal(false);
  };
  console.log(currentSeats, 'currentSeats');
  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={currentSeats.length > 0 ? false : true}>
          Confirm
        </Button>
      </div>
      <LegendWrapper />
      {showSeatsModal && (
        <Modal
          onConfirm={modalClose}
          onChange={onModalChange}
          variant="input"
          value={noOfSeats}
        />
      )}
      {showSeatsConfirmationModal && (
        <Modal
          onConfirm={seatsFinal}
          onChange={onModalChange}
          variant={'confirm'}
          onCancel={finalCancel}
        />
      )}
    </div>
  );
};

export default BookingPage;
