import { useEffect, useState } from "react";
import BookingWrapper from "../../Layout/BookingWrapper/Index";
import Header from "../../Layout/Header/Index";
import Modal from "../../Shared/Modal/Index";
import img from "../../../assets/images/power-button_12080802.png";
import Button from "../../Base/Button/Index";
import LegendWrapper from "../LegendWrapper/Index";
import { getItem, reset, setItem } from "../../../utils/localStorage";
import styles from "./styles.module.css";
import { useNavigate } from "react-router-dom";
import { appConstants } from "../../../utils/AppConstants";

const SeatBooking = () => {
  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 [onOfSeats, setNoOfSeats] = useState();

  useEffect(() => {
    getSelectedSeats();
  }, []);

  const data = [
    {
      row_id: 1,
      columnData: [
        {
          id: 0,
          status: "aisle",
        },
        {
          id: 1,
          status: "reserved",
        },
        {
          id: 2,
          status: "available",
        },
        {
          id: 3,
          status: "reserved",
        },
        {
          id: 4,
          status: "available",
        },
        {
          id: 0,
          status: "aisle",
        },
        {
          id: 5,
          status: "available",
        },
        {
          id: 6,
          status: "reserved",
        },
        {
          id: 7,
          status: "available",
        },
        {
          id: 8,
          status: "reserved",
        },
        {
          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: 5,
          status: "available",
        },
        {
          id: 0,
          status: "aisle",
        },
        {
          id: 6,
          status: "available",
        },
        {
          id: 7,
          status: "available",
        },
        {
          id: 8,
          status: "available",
        },
        {
          id: 9,
          status: "available",
        },
        {
          id: 10,
          status: "available",
        },
      ],
    },
    {
      row_id: 3,
      columnData: [
        {
          id: 1,
          status: "available",
        },
        {
          id: 2,
          status: "available",
        },
        {
          id: 3,
          status: "available",
        },
        {
          id: 4,
          status: "available",
        },
        {
          id: 5,
          status: "available",
        },
        {
          id: 0,
          status: "aisle",
        },
        {
          id: 6,
          status: "available",
        },
        {
          id: 7,
          status: "available",
        },
        {
          id: 8,
          status: "available",
        },
        {
          id: 9,
          status: "available",
        },
        {
          id: 10,
          status: "available",
        },
      ],
    },
    {
      row_id: 4,
      columnData: [
        {
          id: 1,
          status: "available",
        },
        {
          id: 2,
          status: "available",
        },
        {
          id: 3,
          status: "available",
        },
        {
          id: 4,
          status: "available",
        },
        {
          id: 5,
          status: "available",
        },
        {
          id: 0,
          status: "aisle",
        },
        {
          id: 6,
          status: "available",
        },
        {
          id: 7,
          status: "available",
        },
        {
          id: 8,
          status: "available",
        },
        {
          id: 9,
          status: "available",
        },
        {
          id: 10,
          status: "available",
        },
      ],
    },
    {
      row_id: 5,
      columnData: [
        {
          id: 1,
          status: "available",
        },
        {
          id: 2,
          status: "available",
        },
        {
          id: 3,
          status: "available",
        },
        {
          id: 4,
          status: "available",
        },
        {
          id: 5,
          status: "available",
        },
        {
          id: 0,
          status: "aisle",
        },
        {
          id: 6,
          status: "available",
        },
        {
          id: 7,
          status: "available",
        },
        {
          id: 8,
          status: "available",
        },
        {
          id: 9,
          status: "available",
        },
        {
          id: 10,
          status: "available",
        },
      ],
    },
    {
      row_id: 6,
      columnData: [
        {
          id: 1,
          status: "available",
        },
        {
          id: 2,
          status: "available",
        },
        {
          id: 3,
          status: "available",
        },
        {
          id: 4,
          status: "available",
        },
        {
          id: 5,
          status: "available",
        },
        {
          id: 0,
          status: "aisle",
        },
        {
          id: 6,
          status: "available",
        },
        {
          id: 7,
          status: "available",
        },
        {
          id: 8,
          status: "available",
        },
        {
          id: 9,
          status: "available",
        },
        {
          id: 10,
          status: "available",
        },
      ],
    },
    {
      row_id: 7,
      columnData: [
        {
          id: 1,
          status: "available",
        },
        {
          id: 2,
          status: "available",
        },
        {
          id: 3,
          status: "available",
        },
        {
          id: 4,
          status: "available",
        },
        {
          id: 5,
          status: "available",
        },
        {
          id: 0,
          status: "aisle",
        },
        {
          id: 6,
          status: "available",
        },
        {
          id: 7,
          status: "available",
        },
        {
          id: 8,
          status: "available",
        },
        {
          id: 9,
          status: "available",
        },
        {
          id: 10,
          status: "available",
        },
      ],
    },
    {
      row_id: 8,
      columnData: [
        {
          id: 0,
          status: "aisle",
        },
        {
          id: 1,
          status: "reserved",
        },
        {
          id: 2,
          status: "available",
        },
        {
          id: 3,
          status: "reserved",
        },
        {
          id: 4,
          status: "available",
        },
        {
          id: 0,
          status: "aisle",
        },
        {
          id: 5,
          status: "available",
        },
        {
          id: 6,
          status: "reserved",
        },
        {
          id: 7,
          status: "available",
        },
        {
          id: 8,
          status: "reserved",
        },
        {
          id: 9,
          status: "available",
        },
      ],
    },
  ];

  const getSelectedSeats = async () => {
    const response = await fetch(`${appConstants.API_URL_SEATS}`);
    const data = await response.json();
    setSelectedSeats(data);
  };

  const editSeatsApi = async (id, body) => {
    try {
      await fetch(`${appConstants.API_URL_SEATS}/${id}`, {
        method: "PATCH",
        headers: {
          "Content-Type": "application/json",
        },
        body: JSON.stringify({ selected: body }),
      });
      getSelectedSeats();
      setCurrentSeats([]);
    } catch (error) {
      console.log(error, "error");
    }
  };

  const createSeatApi = async (body) => {
    await fetch(`${appConstants.API_URL_SEATS}`, {
      method: "POST",
      headers: {
        "Content-Type": "application/json",
      },
      body: JSON.stringify(body),
    });
    getSelectedSeats();
    setCurrentSeats([]);
  };

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

  const onModalChange = (value) => {
    setNoOfSeats(value);
  };

  const modalClose = () => {
    setItem("modal", false);
    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);
      if (found) {
        return currentSeats.filter(
          (e) => !(e.row == rowId && e.seat == columnId)
        );
      } else {
        let obj = {
          row: rowId,
          seat: columnId,
        };
        return [...prev, obj];
      }
    });
  };

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

    if (existingUserSeatMap) {
      await editSeatsApi(userId, currentSeats);
    } else {
      let info = {
        id: userId,
        userid: userId,
        selected: currentSeats,
      };
      await createSeatApi(info);
    }
    setShowSeatsConfirmationModal(false);
  };

  return (
    <div className={styles["seat-booking-wrapper"]}>
      <img
        src={img}
        className={styles["logout"]}
        width={30}
        onClick={() => logout()}
      />
      <div>
        <Header>Choose Seats</Header>
      </div>
      <div>
        <BookingWrapper
          seatData={data}
          selectedSeats={selectedSeats}
          onSeatClick={onSelectSeats}
          currentSeats={currentSeats}
        />
      </div>
      <div className={styles["btn-wrapper"]}>
        <Button size={"md"} onClick={onSeatsConfirm} disabled={currentSeats.length > 0 ? false : true }>
          Confirm
        </Button>
      </div>
      <LegendWrapper />
      {showSeatsModal && (
        <Modal
          onConfirm={modalClose}
          onChange={onModalChange}
          variant="input"
        />
      )}
      {showSeatsConfirmationModal && (
        <Modal
          onConfirm={seatsFinal}
          onChange={onModalChange}
          variant={"confirm"}
          onOfSeats={currentSeats.length}
          onCancel={finalCancel}
        />
      )}
    </div>
  );
};

export default SeatBooking;
