"use client";

import { useState } from "react";
import { Icon } from "@iconify/react";
import dayjs from "dayjs";

const TimeSlotReservation = () => {
    const [formData, setFormData] = useState({
        from_date: "",
        to_date: "",
        start_time: "",
        end_time: "",
        interval: "",
    });
    const [slots, setSlots] = useState([]);
    const [errors, setErrors] = useState({});

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

    const generateSlots = () => {
        const newErrors = {};
        if (!formData.start_time) newErrors.start_time = "Start time is required";
        if (!formData.end_time) newErrors.end_time = "End time is required";
        if (!formData.interval || isNaN(formData.interval) || formData.interval <= 0)
            newErrors.interval = "Valid interval is required";

        setErrors(newErrors);
        if (Object.keys(newErrors).length > 0) return;

        const slotList = [];
        const [startHour, startMinute] = formData.start_time.split(":").map(Number);
        const [endHour, endMinute] = formData.end_time.split(":").map(Number);
        const start = dayjs().hour(startHour).minute(startMinute).second(0);
        const end = dayjs().hour(endHour).minute(endMinute).second(0);

        let current = start;
        while (current.isBefore(end) || current.isSame(end)) {
            slotList.push({
                slot_time: current.format("HH:mm:ss"),
                interval: Number(formData.interval),
                enabled: false,
            });
            current = current.add(Number(formData.interval), "minute");
        }
        setSlots(slotList);
    };


    const handleSlotToggle = (index) => {
        const updatedSlots = [...slots];
        updatedSlots[index].enabled = !updatedSlots[index].enabled;
        setSlots(updatedSlots);
    };

    const handleSubmit = (e) => {
        e.preventDefault();
        const payload = { ...formData, interval: Number(formData.interval), slots };
        console.log("Final Payload:", payload);
        // Submit to API or further processing here
    };

    return (
        <div className="container mt-4">
            <button
                className="btn btn-primary mb-3"
                data-bs-toggle="modal"
                data-bs-target="#reservationModal"
            >
                <Icon icon="ic:baseline-plus" /> Create Reservation
            </button>

            <div className="modal fade" id="reservationModal" tabIndex="-1">
                <div className="modal-dialog modal-lg modal-dialog-centered">
                    <div className="modal-content p-4">
                        <h5 className="modal-title mb-3">Create Time Slot Reservation</h5>
                        <form onSubmit={handleSubmit}>
                            <div className="row mb-3">
                                <div className="col-md-6">
                                    <label className="form-label">From Date</label>
                                    <input
                                        type="date"
                                        className="form-control"
                                        name="from_date"
                                        value={formData.from_date}
                                        onChange={handleChange}
                                    />
                                </div>
                                <div className="col-md-6">
                                    <label className="form-label">To Date</label>
                                    <input
                                        type="date"
                                        className="form-control"
                                        name="to_date"
                                        value={formData.to_date}
                                        onChange={handleChange}
                                    />
                                </div>
                            </div>
                            <div className="row mb-3">
                                <div className="col-md-4">
                                    <label className="form-label">Start Time</label>
                                    <input
                                        type="time"
                                        className={`form-control ${errors.start_time ? 'is-invalid' : ''}`}
                                        name="start_time"
                                        value={formData.start_time}
                                        onChange={handleChange}
                                    />
                                </div>
                                <div className="col-md-4">
                                    <label className="form-label">End Time</label>
                                    <input
                                        type="time"
                                        className={`form-control ${errors.end_time ? 'is-invalid' : ''}`}
                                        name="end_time"
                                        value={formData.end_time}
                                        onChange={handleChange}
                                    />
                                </div>
                                <div className="col-md-4">
                                    <label className="form-label">Interval (minutes)</label>
                                    <input
                                        type="number"
                                        className={`form-control ${errors.interval ? 'is-invalid' : ''}`}
                                        name="interval"
                                        value={formData.interval}
                                        onChange={handleChange}
                                        min="1"
                                    />
                                </div>
                            </div>
                            <button
                                type="button"
                                className="btn btn-outline-secondary mb-3"
                                onClick={generateSlots}
                            >
                                Generate Time Slots
                            </button>

                            {slots.length > 0 && (
                                <div className="border p-3 rounded">
                                    <h6>Generated Time Slots:</h6>
                                    <div className="d-flex flex-wrap gap-2">
                                        {slots.map((slot, index) => (
                                            <div key={index} className="form-check">
                                                <input
                                                    className="form-check-input"
                                                    type="checkbox"
                                                    checked={slot.enabled}
                                                    onChange={() => handleSlotToggle(index)}
                                                    id={`slot-${index}`}
                                                />
                                                <label
                                                    className="form-check-label"
                                                    htmlFor={`slot-${index}`}
                                                >
                                                    {slot.slot_time}
                                                </label>
                                            </div>
                                        ))}
                                    </div>
                                </div>
                            )}

                            <div className="d-flex justify-content-end mt-4">
                                <button type="submit" className="btn btn-primary">
                                    Submit Reservation
                                </button>
                            </div>
                        </form>
                    </div>
                </div>
            </div>
        </div>
    );
};

export default TimeSlotReservation;
