import Button from '@/components/ui/Button';
import Head from 'next/head';
import Image from 'next/image';
import { useRouter } from 'next/router';
import { Col, Row, Spinner } from 'react-bootstrap';
import style from './index.module.scss';
import { useGetCategoryListQuery } from '@/lib/redux/services/general/category.api';
import { setBookingCategory } from '@/lib/redux/slices/booking.slice';
import { useDispatch, useSelector } from 'react-redux';
import { useEffect, useState } from 'react';
import { RootState } from '@reduxjs/toolkit/query';

const CreateNewBooking = () => {
  const router = useRouter();
  const dispatch = useDispatch();

  // Get category list
  const { data, error, isLoading } = useGetCategoryListQuery();

  // Get selected category from Redux
  const selectedCategoryIdFromStore = useSelector((state: RootState) => state.bookingJourney?.category);

  // Local state for UI highlight
  const [selectedCategoryId, setSelectedCategoryId] = useState(null);

  useEffect(() => {
    if (selectedCategoryIdFromStore) {
      setSelectedCategoryId(selectedCategoryIdFromStore);
    }
  }, [selectedCategoryIdFromStore]);

  const handleCategorySelect = (categoryId) => {
    dispatch(setBookingCategory(categoryId));
    router.push('/auth/storage-unit');
  };

  return (
    <>
      <Head>
        <title>Select Category | Deliver X</title>
      </Head>

      <div className={`w-100 px-sm-5 ${style.booking}`}>
        <h4 className="auth-page-title text-center">Select Category</h4>

        {isLoading ? (
          <div className="d-flex justify-content-center align-items-center" style={{ height: '200px' }}>
            <Spinner animation="border" variant="primary" />
          </div>
        ) : error ? (
          <p className="text-danger text-center">Error fetching categories!</p>
        ) : (
          <Row className={`w-100 ${style.marginTop} gy-3`}>
            {data?.data?.map((category) => (
              <Col md={6} sm={6} key={category._id}>
                <div
                  onClick={() => handleCategorySelect(category._id)}
                  className={`
                    ${style.createNewBooking}
                    ${selectedCategoryId === category._id ? style.active : ''}
                    gap-3 cursor-pointer d-flex align-items-center px-xxl-4 px-md-3 px-sm-2
                  `}
                >
                  {category.image?.file ? (
                    <Image
                      src={`${process.env.NEXT_PUBLIC_MEDIA_URL}/${category.image.file}`}
                      width={34}
                      height={34}
                      alt={category.name}
                    />
                  ) : (
                    <span className="icon-default fs-3">Icon</span>
                  )}
                  <h5 className="mb-0 fw-bold">{category.name}</h5>
                </div>
              </Col>
            ))}

            <Col md={12} className="text-center">
              <Button className="btn btn-feature mt-4" size="lg">
                Others
              </Button>
            </Col>
          </Row>
        )}
      </div>
    </>
  );
};

export default CreateNewBooking;
