import { useState, useEffect } from "react";
import { Header } from "../components/Layout/Card/Header";
import {
  getSeatLayout,
  getReservedSeats,
  getUserReservedSeats,
  saveSeat,
  updateSeat,
} from "../Api/Api";
import { Legend } from "../components/Layout/Legend/Legend";
import { SeatSelectionComponent } from "../components/Top-level/SeatSelection/Index";
import style from "./Styles.module.css";
import { useNavigate } from "react-router-dom";
import { Screen } from "../components/Top-level/Screen/Screen";
import { toast } from "react-toastify";

function SeatBooking() {
  const navigate = useNavigate();
  const userId =
    sessionStorage.getItem("userId") || localStorage.getItem("userId");
  const storedLimit = sessionStorage.getItem("seatLimit");
  const initialLimit = storedLimit ? Number(storedLimit) : 0;

  const [seatLayout, setSeatLayout] = useState([]);
  const [reservedSeats, setReservedSeats] = useState([]);
  const [userReservedSeats, setUserReservedSeats] = useState([]);
  const [userSeatRecordId, setUserSeatRecordId] = useState(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState(null);

  useEffect(() => {
    let isMounted = true;

    async function fetchSeatData() {
      try {
        setLoading(true);
        setError(null);

        const [layoutData, allReserved, userRecord] = await Promise.all([
          getSeatLayout(),
          getReservedSeats(),
          userId ? getUserReservedSeats(userId) : Promise.resolve(null),
        ]);

        if (isMounted) {
          setSeatLayout(layoutData);
          setReservedSeats(allReserved);
          if (userRecord) {
            setUserReservedSeats(userRecord.seats || []);
            setUserSeatRecordId(userRecord.id || null);
          }
        }
      } catch (err) {
        if (isMounted) {
          setError("Failed to load seat data. Please try again.");
          console.error("Error fetching seat data:", err);
        }
      } finally {
        if (isMounted) {
          setLoading(false);
        }
      }
    }

    fetchSeatData();
    return () => {
      isMounted = false;
    };
  }, [userId]);

  const handleConfirm = async ({ seats, clearSelection }) => {
    try {
      const validSeats = seats.filter((s) => typeof s === "string" && s.trim());

      if (validSeats.length < initialLimit) {
        toast.info(`Please select ${initialLimit} seat(s).`);
        return;
      }
      const latestReservedSeats = await getReservedSeats();

      const conflictingSeats = validSeats.filter(
        (seat) =>
          latestReservedSeats.includes(seat) &&
          !userReservedSeats.includes(seat)
      );
      if (conflictingSeats.length > 0) {
        toast.error(
          `The following seat(s) were just taken:${conflictingSeats.join(",")}`
        );
        return;
      }

      let response;
      if (userSeatRecordId) {
        response = await updateSeat({
          id: userSeatRecordId,
          userId,
          seats: validSeats,
        });
      } else {
        response = await saveSeat({ userId, seats: validSeats });
        setUserSeatRecordId(response.id);
      }

      const [allReserved, userRecord] = await Promise.all([
        getReservedSeats(),
        getUserReservedSeats(userId),
      ]);

      setReservedSeats(allReserved);
      setUserReservedSeats(userRecord?.seats || []);
      sessionStorage.setItem("selectedSeats", JSON.stringify(validSeats));

      if (typeof clearSelection === "function") clearSelection();
      navigate("/booking-summary", { state: { success: true } });
    } catch (error) {
      console.error("Error saving seats:", error);
      toast.error("Failed to reserve seats. Please try again.");
    }
  };

  if (loading) {
    return (
      <div className={style.loadingContainer}>
        <div className={style.spinner}></div>
        <p style={{ color: "#fff" }}>Loading seat data...</p>
      </div>
    );
  }

  if (error) {
    return (
      <div className={style.errorContainer}>
        <p>{error}</p>
        <button onClick={() => window.location.reload()}>Retry</button>
      </div>
    );
  }

  return (
    <div className={style.pageContainer}>
      <div className={style.head}>
        <Header title="Choose Your Seats" Color="#fff" />
      </div>
      <div className={style.screen}>
        <Screen className={style.mainscreen} />
      </div>
      <div className={style.container}>
        <SeatSelectionComponent
          key={userSeatRecordId || "new-user"}
          seats={seatLayout}
          reservedSeats={reservedSeats.filter(
            (s) => !userReservedSeats.includes(s)
          )}
          selectedSeats={userReservedSeats}
          seatLimit={initialLimit}
          userId={userId}
          onClick={handleConfirm}
        />
      </div>
      <div className={style.footer}>
        <Legend />
      </div>
    </div>
  );
}

export default SeatBooking;
