"use client";
import axios from "axios";
import { useRouter, useSearchParams } from "next/navigation";
import React, { Suspense, useEffect, useState } from "react";
import PhoneInput from "react-phone-input-2";
import { Baseurl, RestaruntBranch } from "@utils/BaseUrl.utils";
import client from "@auth";
import { format12HoursTime, formatTime } from "@utils/CommonFunction";
import PageLoader from "@/components/common-component/PageLoader";

const UpdateReservationFormComponentInner = ({ restaurantbranch }) => {
    const searchparams = useSearchParams()
    const reservationName = searchparams.get('name')
    const RestaurantBranch = searchparams.get('restaurantbranch')


    const router = useRouter();

    const sendsms = true
    const sendmail = true

    const [currentStep, setCurrentStep] = useState(1);
    const [slots, setSlots] = useState([]);
    const [selectedSlot, setSelectedSlot] = useState(null);
    const [slotMessage, setSlotMessage] = useState("");
    const [slotTime, setSlotTime] = useState("")

    const [formData, setFormData] = useState({
        name: "",
        email: "",
        number: "",
    });

    const [errors, setErrors] = useState({
        name: "",
        email: "",
        number: "",
    });
    const [slotFormData, setSlotFormData] = useState({
        partySize: "",
        reservationDate: ""
    });

    const [slotErrors, setSlotErrors] = useState({
        partySize: "",
        reservationDate: ""
    });

    useEffect(() => {
        getReservation()
    }, [])

    const getReservation = async () => {
        try {
            const res = await client.get(`/Dine360%20Reservation/${reservationName}?fields=["*"]`);
            const response = res?.data?.data
            const customerDetails = {
                name: response?.customer_name,
                email: response?.email,
                number: response?.phonenumber,
            }
            setFormData(customerDetails)
            const reservationDetails = {
                partySize: response?.partysize.toString(),
                reservationDate: response?.reservation_date
            }
            setSlotFormData(reservationDetails)

            const selectedTime = response?.timeslot;
            setSlotTime(selectedTime)

        } catch (error) {
            console.log("error", error)
        }
    }

    useEffect(() => {
        if (
            slotFormData.reservationDate &&
            slotFormData.partySize &&
            slotFormData.partySize.trim() !== "" && slotTime
        ) {
            generateSlots();
        }
        // eslint-disable-next-line react-hooks/exhaustive-deps
    }, [slotFormData.reservationDate, slotFormData.partySize]);

    const generateSlots = async () => {
        setSlotMessage("");
        // setSelectedSlot(null);

        const newErrors = {};
        let hasError = false;

        if (!slotFormData.partySize.trim()) {
            newErrors.partySize = "Party size is required";
            hasError = true;
        }

        if (!slotFormData.reservationDate.trim()) {
            newErrors.reservationDate = "Reservation date is required";
            hasError = true;
        }

        if (hasError) {
            setSlotErrors(newErrors);
            setSlots([]); // clear slots if invalid
            return;
        }

        const originalDate = new Date(slotFormData.reservationDate);
        const formattedDate = originalDate
            .toLocaleDateString("en-GB")
            .split("/")
            .map((part, i) => (i === 2 ? part.slice(2) : part))
            .join("/");

        const body = {
            // branch: "Malaysia",
            reservationDate: formattedDate,
            partySize: Number(slotFormData.partySize),
            restaurantbranch: RestaurantBranch
        };

        try {
            const res = await axios.post(`${Baseurl}/reservation/time-slots`, body);
            const receivedSlots = res?.data?.slots || [];

            if (receivedSlots.every((slot) => slot.occupancyavailable === 0)) {
                setSlotMessage("No slots available.");
            } else if (receivedSlots.every((slot) => slot.tableavailable === 0)) {
                setSlotMessage("No slots available for your party size.");
            } else {
                setSlotMessage("");
            }

            setSlots(receivedSlots);

            setSelectedSlot((prev) => {
                const matchingSlot = receivedSlots.find(slot => slot.slot_time === slotTime);
                return matchingSlot || null;
            });
            // ✅ Match the correct slot by value (e.g., slot_time)
            const matchedSlot = receivedSlots.find(
                (slot) => slot.slot_time === selectedSlot?.slot_time
            );
            if (matchedSlot) {
                setSelectedSlot(matchedSlot); // ✅ default select from slots
            }
        } catch (error) {
            console.error("Error fetching slots:", error);
        }
    };


    const handleChange = (e) => {
        const { name, value } = e.target;
        setFormData((prev) => ({
            ...prev,
            [name]: value
        }));
        setErrors((prev) => ({
            ...prev,
            [name]: ""
        }));
    };

    const handlePhoneChange = (value) => {
        setFormData((prev) => ({
            ...prev,
            number: value
        }));
        setErrors((prev) => ({
            ...prev,
            number: ""
        }));
    };

    const handleSlotChange = (e) => {
        const { name, value } = e.target;
        setSlotFormData((prev) => ({
            ...prev,
            [name]: value
        }));
        setSlotErrors((prev) => ({
            ...prev,
            [name]: ""
        }));
    };


    const nextStep = () => {
        let hasError = false;
        const newErrors = {};

        if (!formData.name.trim()) {
            newErrors.name = "Full Name is required";
            hasError = true;
        }

        if (!formData.email.trim()) {
            newErrors.email = "Email is required";
            hasError = true;
        }

        if (!formData.number || formData.number.length < 8) {
            newErrors.number = "Valid phone number is required";
            hasError = true;
        }

        if (hasError) {
            setErrors(newErrors);
            return;
        }
        if (currentStep < 4) {
            setCurrentStep(currentStep + 1);
        }
    };

    const prevStep = () => {
        if (currentStep > 1) {
            setCurrentStep(currentStep - 1);
        }
    };
    console.log("selectedSlot", selectedSlot)
    const SubmitReservation = async (e) => {
        e.preventDefault();

        if (!selectedSlot || selectedSlot == null) {
            alert("Select any one Slot")
            return;
        }

        const payload = {
            customer: "Navya",
            customer_name: formData.name,
            phonenumber: `+${formData.number}`,
            email: formData.email,
            reservation_date: slotFormData.reservationDate,
            partysize: slotFormData.partySize,
            timeslot: selectedSlot?.slot_time,
            available_tables: selectedSlot?.availabletables?.length ? selectedSlot.availabletables.join(", ") : "",
            best_tables: selectedSlot?.besttables?.length ? selectedSlot.besttables.join(", ") : "",
            status: "Reserved",
            source: "Website",
            special_requests: "No Special Requests",
            table_assigned: selectedSlot?.choosentable?.name || "",
            tablename: selectedSlot?.choosentable?.tablename || "",
        };

        const notification = {
            sendSms: sendsms,
            sendMail: sendmail,
            smsTo: `+${formData.number}`,
            mailTo: formData.email,
            mailFrom: `"Dine360" <admin@metatronnest.com>`,
            subject: "Welcome to Dine360",
            title: `Hello ${formData.name}!`,
            body: "Thanks for signing up—let us know if you have any questions."
        };

        try {
            const res = await client.put(`/Dine360%20Reservation/${reservationName}`, payload);

            try {
                const notificationResponse = await axios.post(`${Baseurl}/notifications/send`, notification, {
                    headers: {
                        "x-api-key": "1234567890"
                    }
                });
                console.log("Notification Sent:", notificationResponse.data);
            } catch (notificationError) {
                console.error("Notification Error:", notificationError?.response?.data || notificationError.message);
            }
            setCurrentStep(currentStep + 1);
            setFormData({
                name: "",
                email: "",
                number: "",
            })
            setSlotFormData({
                partySize: "",
                reservationDate: ""
            })
            setErrors({
                name: "",
                email: "",
                number: "",
            })
            setSlotErrors({
                partySize: "",
                reservationDate: ""
            })
        } catch (reservationError) {
            console.error("Reservation Error:", reservationError?.response?.data || reservationError.message);
        }

    };

    const backtoHomeButton = () => {
        router.push(`/admin/reserved-users/?restaurantbranch=${restaurantbranch}`)
    }

    return (
        <div className="row justify-content-center" style={{ marginBottom: '100px' }}>
            <div className='col-xxl-5 col-xl-6 col-lg-7 col-md-9'>
                <div className='card p-lg-3'>
                    <div className='card-body'>
                        <h6 className='mb-4 text-xl'>Table Reservation By Following Step</h6>
                        <p className='text-neutral-500'>
                            Fill up your details and proceed next steps.
                        </p>
                        {/* Form Wizard Start */}
                        <div className='form-wizard'>
                            <form action='#' method='post'>
                                <div className='form-wizard-header overflow-x-auto scroll-sm pb-8 my-32'>
                                    <ul className='list-unstyled form-wizard-list style-two'>
                                        <li
                                            className={`form-wizard-list__item
                      ${[2, 3, 4].includes(currentStep) && "activated"}
                    ${currentStep === 1 && "active"} `}
                                        >
                                            <div className='form-wizard-list__line'>
                                                <span className='count'>1</span>
                                            </div>
                                            <span className='text text-xs fw-semibold'>
                                                Customer
                                            </span>
                                        </li>
                                        <li
                                            className={`form-wizard-list__item
                      ${[3, 4].includes(currentStep) && "activated"}
                    ${currentStep === 2 && "active"} `}
                                        >
                                            <div className='form-wizard-list__line'>
                                                <span className='count'>2</span>
                                            </div>
                                            <span className='text text-xs fw-semibold'>
                                                Restaurant
                                            </span>
                                        </li>
                                        <li
                                            className={`form-wizard-list__item
                    //   ${[4].includes(currentStep) && "activated"}
                    ${currentStep === 3 && "active"} `}
                                        >
                                            <div className='form-wizard-list__line'>
                                                <span className='count'>3</span>
                                            </div>
                                            <span className='text text-xs fw-semibold'>Completed</span>
                                        </li>
                                        {/* <li
                                            className={`form-wizard-list__item

                    ${currentStep === 4 && "active"} `}
                                        >
                                            <div className='form-wizard-list__line'>
                                                <span className='count'>4</span>
                                            </div>
                                            <span className='text text-xs fw-semibold'>Completed</span>
                                        </li> */}
                                    </ul>
                                </div>
                                <fieldset
                                    className={`wizard-fieldset ${currentStep === 1 && "show"} `}
                                >
                                    <h6 className='text-md text-neutral-500'>
                                        Personal Information
                                    </h6>
                                    <div className='row gy-3'>
                                        <div className='col-sm-12'>
                                            <div>
                                                <label htmlFor="name" className="form-label fw-semibold text-primary-light text-sm mb-8">
                                                    Full Name <span className="text-danger-600">*</span>
                                                </label>
                                                <input
                                                    type="text"
                                                    className="form-control radius-8"
                                                    id="name"
                                                    name="name"
                                                    value={formData.name}
                                                    onChange={handleChange}
                                                    placeholder="Enter Full Name"
                                                // disabled
                                                />
                                                {errors.name && (
                                                    <div className="text-danger text-sm mt-1">{errors.name}</div>
                                                )}
                                            </div>
                                        </div>
                                        <div className='col-sm-12'>
                                            <div>
                                                <label htmlFor="email" className="form-label fw-semibold text-primary-light text-sm mb-8">
                                                    Email <span className="text-danger-600">*</span>
                                                </label>
                                                <input
                                                    type="email"
                                                    className="form-control radius-8"
                                                    id="email"
                                                    name="email"
                                                    value={formData.email}
                                                    onChange={handleChange}
                                                    // disabled
                                                    placeholder="Enter email address"
                                                />
                                                {errors.email && (
                                                    <div className="text-danger text-sm mt-1">{errors.email}</div>
                                                )}
                                            </div>
                                        </div>
                                        <div className='col-12'>
                                            <div>
                                                <label htmlFor="number" className="form-label fw-semibold text-primary-light text-sm mb-8">
                                                    Phone <span className="text-danger-600">*</span>
                                                </label>
                                                <PhoneInput
                                                    country={'us'} // Default country
                                                    value={formData.number}
                                                    onChange={handlePhoneChange}
                                                    // disabled
                                                    inputProps={{
                                                        name: 'number',
                                                        required: true,
                                                        className: 'form-control radius-8 w-100'
                                                    }}
                                                />
                                                {errors.number && (
                                                    <div className="text-danger text-sm mt-1">{errors.number}</div>
                                                )}
                                            </div>
                                        </div>

                                        <div className='form-group text-end'>
                                            <button
                                                onClick={nextStep}
                                                type='button'
                                                className='form-wizard-next-btn btn btn-bg-theme px-32'
                                            >
                                                Next
                                            </button>
                                        </div>
                                    </div>
                                </fieldset>
                                <fieldset
                                    className={`wizard-fieldset ${currentStep === 2 && "show"} `}
                                >
                                    <h6 className='text-md text-neutral-500'>
                                        Reservation Information
                                    </h6>
                                    <div className='row gy-3'>
                                        <div className="col-12">
                                            <div>
                                                <label htmlFor="partySize" className="form-label fw-semibold text-primary-light text-sm mb-2">
                                                    Party Size <span className="text-danger-600">*</span>
                                                </label>
                                                <select
                                                    className="form-select radius-8"
                                                    id="partySize"
                                                    name="partySize"
                                                    value={slotFormData.partySize}
                                                    onChange={handleSlotChange}
                                                >
                                                    <option value="">Select party size</option>
                                                    {[...Array(12)].map((_, i) => (
                                                        <option key={i + 1} value={i + 1}>{i + 1}</option>
                                                    ))}
                                                </select>
                                                {slotErrors.partySize && (
                                                    <div className="text-danger text-sm mt-1">{slotErrors.partySize}</div>
                                                )}
                                            </div>
                                        </div>

                                        <div className='col-sm-12'>
                                            <div >
                                                <label htmlFor="reservationDate" className="form-label fw-semibold text-primary-light text-sm mb-2">
                                                    Reservation Date <span className="text-danger-600">*</span>
                                                </label>
                                                <input
                                                    type="date"
                                                    className="form-control radius-8"
                                                    id="reservationDate"
                                                    name="reservationDate"
                                                    value={slotFormData.reservationDate}
                                                    onChange={handleSlotChange}
                                                />
                                                {slotErrors.reservationDate && (
                                                    <div className="text-danger text-sm mt-1">{slotErrors.reservationDate}</div>
                                                )}
                                            </div>
                                        </div>
                                        {slotMessage && (
                                            <div className="text-danger-500 text-lg mt-2">{slotMessage}</div>
                                        )}

                                        {!slotMessage && slots.length > 0 && (
                                            <div className="mt-3">
                                                <h6 className='text-md text-neutral-500'>
                                                    Select Slot
                                                </h6>
                                                <div className="d-flex flex-wrap gap-2 border p-3 rounded-3">
                                                    {slots.map((slot, index) => {
                                                        const isSelected = slot.slot_time === selectedSlot?.slot_time;
                                                        const isDisabled = !slot.enabled;

                                                        const buttonClass = `
                                                            btn text-sm
                                                            ${isSelected
                                                                ? "bg-success text-white border-success"
                                                                : isDisabled
                                                                    ? "bg-danger-300 opacity-30 text-white border-0 cursor-not-allowed"
                                                                    : "btn-outline-success-500"}
                                                                 `;

                                                        return (
                                                            <button
                                                                key={index}
                                                                type="button"
                                                                className={buttonClass}
                                                                onClick={() => !isDisabled && setSelectedSlot(slot)}
                                                                disabled={isDisabled}
                                                                title={isDisabled ? "Slot not available" : ""}
                                                            >
                                                                {format12HoursTime(slot.slot_time)}
                                                            </button>
                                                        );
                                                    })}

                                                </div>
                                            </div>
                                        )}

                                        <div className='form-group d-flex align-items-center justify-content-end gap-8'>
                                            <button
                                                onClick={prevStep}
                                                type='button'
                                                className='form-wizard-previous-btn btn btn-outline-theme px-32'
                                            >
                                                Back
                                            </button>
                                            <button
                                                onClick={SubmitReservation}
                                                type='button'
                                                className='form-wizard-next-btn btn btn-bg-theme px-32'
                                            >
                                                Submit
                                            </button>
                                        </div>
                                    </div>
                                </fieldset>
                                <fieldset
                                    className={`wizard-fieldset ${currentStep === 3 && "show"} `}
                                >
                                    <div className='text-center mb-40'>
                                        <img
                                            src='/assets/images/gif/success-img3.gif'
                                            alt=''
                                            className='gif-image mb-24'
                                        />
                                        <h6 className='text-md text-neutral-600'>Congratulations </h6>
                                        <p className='text-neutral-400 text-sm mb-0'>
                                            Well done! You have successfully Updated.
                                        </p>
                                    </div>
                                    <div className='form-group d-flex align-items-center justify-content-center'>

                                        <button
                                            type='button'
                                            className='form-wizard-submit btn btn-bg-theme'
                                            onClick={backtoHomeButton}
                                        >
                                            Back to Home
                                        </button>
                                    </div>
                                </fieldset>

                            </form>
                        </div>
                        {/* Form Wizard End */}
                    </div>
                </div>
            </div>
        </div>
    );
};

const UpdateReservationFormComponent = (() => {
    return (
        <Suspense fallback={<PageLoader />}>
            <UpdateReservationFormComponentInner />
        </Suspense>
    )
})

export default UpdateReservationFormComponent;
