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 "../../Base/Screen/Screen";
import { AiOutlineLogout } from "react-icons/ai";
export const Selectseat = ({onLogout}) => {
  const [selectedSeats, setSelectedSeats] = useState([]);
  const [allReservedSeats, setAllReservedSeats] = 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 reserved = users
          .flatMap(u => u.reservedSeats || [])
          .filter(seat => seat);
        setAllReservedSeats(reserved);
       const totalSeats=60;

       const available=totalSeats-reserved.length;
       setAvailableSeats(available);
     })
      .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 (selectedSeats.length < seatCount) {
    toast.info(`Please select ${seatCount} seats`);
    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 || []);

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

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

      const updatedSeats = Array.from(
        new Set([...(currentUser.reservedSeats || []), ...selectedSeats])
      );

      return updateUserReservedSeats(currentUser.id, updatedSeats);
    })
    .then(res => {
      if (res) {
        toast.success("Seats confirmed!");
        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}>
        {/* <div className={styles.logoutButton}><Button variant="secondary" label="Logout" size="sm" onClick={onLogout}/></div> */}
        <h2  className={styles.text}>Choose Seats</h2>
         <Screen/>

        <div className={styles.seatcontainer}>
          <SeatLayout
            allReservedSeats={allReservedSeats}
            onSelectionChange={setSelectedSeats}
            limit={seatCount}
          />
        </div>

        <div className={styles.button}>
          <Button variant="secondary" label="Confirm" size='md' onClick={confirmHandler} disabled={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} />
  </>
  );
};
