import { useEffect, useState } from "react";
import { getAllUsers, updateUserReservedSeats } from "../../../Api/userApi";
import { Button } from "../../Base/Buttons/Button";
import { Legend } from "../Seat-legend/Legend";
import { SeatLayout } from "../SeatLayout/SeatLayout";
import { getCurrentUser } from "../../../auth/authService";
import styles from "./Selectseat.module.css";
import "react-toastify/dist/ReactToastify.css";
import { toast, ToastContainer } from "react-toastify";
import { Modal } from "../../Base/Modal/Modal";
import { SeatSelectForm } from "../../Form/SeatSelectForm/SeatSelectForm";
import { Screen } from "../../Shared/Screen/Screen";
import { AiOutlineLogout } from "react-icons/ai";

export const Selectseat = ({ onLogout }) => {
  const [selectedSeats, setSelectedSeats] = useState([]);
  const [selectedData, setselectedData] = useState([]);
  const [reservedSeats, setreservedSeats] = useState([]);
  const [seatCount, setSeatCount] = useState(1);
  const [availableSeats, setAvailableSeats] = useState(0);
  const [showSelect, setShowSelect] = useState(true);

  useEffect(() => {
    getAllUsers()
      .then(res => {
        const users = res.data;
        const totalSeats = 60;
        const loggedUser = getCurrentUser();

        const allReserved = users.flatMap(u => u.reservedSeats || []);
        const currentUser = users.find(u => u.phoneNumber === loggedUser.phoneNumber);
        const userSeats = currentUser?.reservedSeats || [];

        const othersReserved = allReserved.filter(seat => !userSeats.includes(seat));

        setselectedData(userSeats);
        setreservedSeats(othersReserved);

        const available = totalSeats - allReserved.length;
        setAvailableSeats(available);

        if (userSeats.length > 0) {
          setSeatCount(userSeats.length);
          setShowSelect(false); // skip modal for existing users
        }
      })
      .catch(err => {
        console.error("Error fetching users", err);
        toast.error("Failed to load seat data.");
      });
  }, []);

  const confirmHandler = () => {
    const user = getCurrentUser();

    if (!user || !user.phoneNumber?.trim()) {
      toast.warn("User not logged in");
      return;
    }

    if (selectedData.length === 0 && selectedSeats.length < seatCount) {
      toast.info(`Please select ${seatCount} seat(s)`);
      return;
    }

    getAllUsers()
      .then(res => {
        const users = res.data;
        const currentUser = users.find(u => u.phoneNumber === user.phoneNumber);

        if (!currentUser) {
          toast.error("User not found");
          return;
        }

        const latestReserved = users
          .flatMap(u => u.reservedSeats || [])
          .filter(seat => !currentUser.reservedSeats.includes(seat));

        const conflictSeats = selectedSeats.filter(seat =>
          latestReserved.includes(seat)
        );

        if (conflictSeats.length > 0) {
          toast.error(`The following seat(s) were just taken: ${conflictSeats.join(", ")}`);
          return;
        }

        return updateUserReservedSeats(currentUser.id, selectedSeats);
      })
      .then(res => {
        if (res) {
          toast.success("Seats updated!");
          setSelectedSeats([]);
          setTimeout(() => {
            window.location.replace("/success");
          }, 1000);
        }
      })
      .catch(err => {
        console.error("Error confirming seats", err);
        toast.error("Failed to confirm seats");
        setTimeout(() => {
          window.location.replace("/error");
        }, 1000);
      });
  };

  const handleModal = () => {
    setShowSelect(false);
  };

  const seatOptions = Array.from({ length: availableSeats }).map((_, i) => ({
    value: i + 1,
    label: `${i + 1} ${i + 1 === 1 ? "seat" : "seats"}`
  }));

  return (
    <>
      <div className={styles.logoutButton}>
        <AiOutlineLogout onClick={onLogout} />
      </div>
      <div className={styles.container}>
        <h2 className={styles.text}>Choose Seats</h2>
        <Screen />

        <div className={styles.seatcontainer}>
          <SeatLayout
            selectedSeats={selectedSeats}
            reservedSeats={reservedSeats}
            currentReservedSeats={selectedData}
            limit={seatCount}
            onSelectionChange={setSelectedSeats}
          />
        </div>

        <div className={styles.button}>
          <Button
            variant="secondary"
            label="Confirm"
            size="md"
            onClick={confirmHandler}
            disabled={selectedData.length === 0 && selectedSeats.length !== seatCount}
          />
        </div>

        <div className={styles.legend}>
          <Legend />
        </div>
      </div>

      {showSelect && (
        <Modal
          title="Choose Number of Seats"
          availableSeats={availableSeats}
          seatCount={seatCount}
          setSeatCount={setSeatCount}
          onClose={handleModal}
        >
          <SeatSelectForm
            seatOptions={seatOptions}
            seatCount={seatCount}
            setSeatCount={setSeatCount}
            onClose={handleModal}
          />
        </Modal>
      )}

      <ToastContainer position="top-right" autoClose={3000} />
    </>
  );
};
