import { get, post } from "@/api1/apiUtils";
import Footer from "@/components/footer/Footer";
import Header from "@/components/header/Header";
import CustomImage from "@/helper/customImage";
import { useRouter } from "next/router";
import { useEffect, useState } from "react";
import Modal from 'react-bootstrap/Modal';
import ToastMessage from "@/helper/toast/ToastMessage";
import { titleToSlug } from "@/helper/titleToSlug";
import { getUser } from "@/helper/getUser";



export interface Hotel {
    id: number;
    hotel_name: string;
    description: string;
    name: string;
    address: {
        street: string;
        city: string;
        state: string;
        country: string;
        postalCode: string;
    };
    price: number;
    images?: String[];
    location: string;

}


const Index = () => {
    const router = useRouter();
    const { checkInDate, checkOutDate, adults, children } = router.query;
    const [searchData, setSearchData] = useState([]);
    const [showModal, setShowModal] = useState(false);
    const [selectedHotel, setSelectedHotel] = useState<Hotel | null>(null);

    useEffect(() => {
        if (!router?.isReady) return;

        async function fetchSearchResult() {
            try {
                const res = await get(`/search`, { checkInDate, checkOutDate, adults, children }) as any;
                setSearchData(res?.results);
            } catch (error) {
                console.error('Error fetching search results:', error);
            }
        }

        fetchSearchResult();
    }, [router?.isReady]);

    const handleBookNow = (hotel: Hotel) => {
        setSelectedHotel(hotel);
        setShowModal(true);
    };

    const handleCloseModal = () => {
        setShowModal(false);
    };

    return (
        <>
            <Header />
            <div className="container mt-4">
                <h4 className="find-srch-title">Best Hotels for You</h4>
                <div className="row">
                    <div className="col-md-8">
                        <div className="row g-3">
                            {searchData?.length > 0 && searchData?.map((s: any) => (
                                <div className="col-md-12 mt-3" key={s?.id} onClick={() => {
                                    router.push(`/${s?.id}/${titleToSlug(s?.hotel_name)}`)
                                }}>
                                    <div className="srch-results-boxvw">
                                        <div className="row">
                                            <div className="col-md-5">
                                                <div className="srch-img">
                                                    <CustomImage
                                                        src={s?.images[0]}
                                                        alt="hotel-image"
                                                        className="img-fluid"
                                                    />
                                                </div>
                                            </div>
                                            <div className="col-md-7">
                                                <h5 className="title">{s?.hotel_name}</h5>
                                                <p className="details">
                                                    {/* {s?.address?.street}, {s?.address?.city}, {s?.address?.state}, {s?.address?.country}, {s?.address?.postalCode} */}
                                                    {s?.location}
                                                </p>
                                                <h6 className="details">Price : ₹<b>{s?.lowest_price}</b></h6>
                                                <div className="bk-btn-o">
                                                    <button className="searchs-book-btns" onClick={() => handleBookNow(s)}>Book Now</button>
                                                </div>
                                                <hr />
                                                <div className="d-flex justify-content-between">
                                                    <div className="srch-amit-dtlsvws"><i className="bi bi-person-circle"></i> {s?.total_capacity} GUESTS</div>
                                                    <div className="srch-amit-dtlsvws">FULL INFO <i className="bi bi-arrow-right"></i></div>
                                                </div>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            ))}
                        </div>
                    </div>
                    <div className="col-md-4 mt-3">
                        <SearchBoxDate />
                    </div>
                </div>
            </div>
            <Footer />


            <Modal show={showModal} onHide={handleCloseModal}>
                <Modal.Header closeButton>
                    <Modal.Title>Book Hotel</Modal.Title>
                </Modal.Header>
                <Modal.Body>
                    {selectedHotel && (
                        <div>
                            <h5>{selectedHotel?.hotel_name}</h5>
                            <p>{selectedHotel.location}</p>
                            {/* <p>{selectedHotel.address.street}, {selectedHotel.address.city}, {selectedHotel.address.state}, {selectedHotel.address.country}, {selectedHotel.address.postalCode}</p> */}
                            <p>Price: ₹ {selectedHotel.price}</p>

                            <BookingForm
                                hotel={selectedHotel}
                                handleCloseModal={handleCloseModal}
                            />

                        </div>
                    )}
                </Modal.Body>
            </Modal>
        </>
    );
}

export default Index;



const SearchBoxDate = () => {
    return (
        <>
            <div className="srch-results-boxvw form-sticky-vws-box">
                <form action="">
                    <label htmlFor="" className="mt-2 srch-label-form">Check-in date</label>
                    <input type="date" className="srch-input-frmvws" />
                    <label htmlFor="" className="mt-2 srch-label-form">Check-out date</label>
                    <input type="date" className="srch-input-frmvws" />

                    <label htmlFor="" className="mt-2 srch-label-form">Adults</label>
                    <select name="" id="" className="srch-input-frmvws">
                        <option value="">1</option>
                        <option value="">2</option>
                    </select>

                    <label htmlFor="" className="mt-2 srch-label-form">Children</label>
                    <select name="" id="" className="srch-input-frmvws">
                        <option value="">0</option>
                        <option value="">1</option>
                    </select>


                    <div><button className="srch-results-btnsvws mt-4">Search</button></div>
                </form>
            </div>
        </>
    )
}





export const BookingForm = ({ hotel, handleCloseModal }: { hotel: any, handleCloseModal?: any }) => {

    const router = useRouter();
    const { checkInDate, checkOutDate, adults, children } = router.query;
    const [showToast, setShowToast] = useState(false);
    const [toastMessage, setToastMessage] = useState('');
    const [toastVariant, setToastVariant] = useState('');


    const [bookingData, setBookingData] = useState({
        fullName: '',
        checkinDate: checkInDate || '',
        checkoutDate: checkOutDate || '',
        totalPersons: adults || 1,
        totalChildren: children || 0,
        mobileNumber: '',
        email: '',
        roomType: 'Normal',
        specialRequests: '',
        paymentStatus: 'Pending',
        images: ''
    });

    const handleChange = (e: any) => {
        const { name, value } = e.target;
        setBookingData(prevState => ({
            ...prevState,
            [name]: value
        }));
    };

    const handleSubmit = async (e: any) => {
        e.preventDefault();

        try {
            const response = await post('/bookings', { ...bookingData, hotel_id: hotel?.id }, { formData: true });
            if (response.status === 'success') {
                setToastVariant('success');
                setToastMessage('Booking created successfully');
            } else {
                throw new Error('Failed to create booking');
            }
        } catch (error) {
            setToastVariant('danger');
            setToastMessage('Failed to create booking');
        } finally {
            setShowToast(true);
        }
    };

    const handleToastClose = () => {
        setShowToast(false);
        setToastMessage('');
        handleCloseModal()
    };


    useEffect(() => {
        const user = getUser()
        if (user) {
            setBookingData({
                ...bookingData,
                fullName: user?.name,
                email: user?.email,
            })
        }
    }, [])



    return (
        <>
            <ToastMessage show={showToast} onClose={handleToastClose}
                message={toastMessage}
                variant={toastVariant}
            />

            <form onSubmit={handleSubmit}>
                <div className="mb-3">
                    <label htmlFor="fullName" className="form-label">Full Name</label>
                    <input type="text" id="fullName" name="fullName" className="form-control"
                        value={bookingData.fullName} onChange={handleChange} required />
                </div>

                <div className="row">
                    <div className="col-md-6">
                        <div className="mb-3">
                            <label htmlFor="checkinDate" className="form-label">Check-in Date</label>
                            <input type="datetime-local" id="checkinDate" name="checkinDate" className="form-control"
                                value={bookingData.checkinDate} onChange={handleChange} required />
                        </div>
                    </div>
                    <div className="col-md-6">
                        <div className="mb-3">
                            <label htmlFor="checkoutDate" className="form-label">Check-out Date</label>
                            <input type="datetime-local" id="checkoutDate" name="checkoutDate" className="form-control"
                                value={bookingData.checkoutDate} onChange={handleChange} required />
                        </div>
                    </div>
                </div>

                <div className="row">
                    <div className="col-md-6">
                        <div className="mb-3">
                            <label htmlFor="totalPersons" className="form-label">Total Persons</label>
                            <input type="number" id="totalPersons" name="totalPersons" className="form-control"
                                value={bookingData.totalPersons} onChange={handleChange} required />
                        </div>
                    </div>
                    <div className="col-md-6">
                        <div className="mb-3">
                            <label htmlFor="totalChildren" className="form-label">Total Children</label>
                            <input type="number" id="totalChildren" name="totalChildren" className="form-control"
                                value={bookingData.totalChildren} onChange={handleChange} required />
                        </div>
                    </div>
                </div>
                <div className="mb-3">
                    <label htmlFor="mobileNumber" className="form-label">Mobile Number</label>
                    <input type="number" id="mobileNumber" name="mobileNumber" className="form-control"
                        value={bookingData.mobileNumber} onChange={handleChange} required />
                </div>
                <div className="mb-3">
                    <label htmlFor="email" className="form-label">Email</label>
                    <input type="email" id="email" name="email" className="form-control"
                        value={bookingData.email} onChange={handleChange} required />
                </div>

                {/* <div className="mb-3">
                <label htmlFor="roomType" className="form-label">Room Type</label>
                <input type="text" id="roomType" name="roomType" className="form-control"
                    value={bookingData.roomType} onChange={handleChange} required />
            </div> */}



                <div className="mb-3">
                    <label htmlFor="qr" className="form-label">Pay Advance for Quick Booking</label>
                    <img src="/images/qr.jpeg" alt="" className="qr" />

                </div>

                <div className="mb-3">
                    <label htmlFor="imageUpload" className="form-label">Upload Screenshot Advance Payment</label>
                    <input
                        type="file"
                        className="form-control"
                        id="imageUpload"
                        accept="image/*"
                        onChange={handleChange}
                        multiple
                    />
                </div>


                <div className="mb-3">
                    <label htmlFor="specialRequests" className="form-label">Message or Suggestion</label>
                    <textarea id="specialRequests" name="specialRequests" className="form-control"
                        value={bookingData.specialRequests} onChange={handleChange}></textarea>
                </div>

                <button type="submit" className="btn btn-primary">Book Now</button>
            </form>

        </>
    );
};

