"use client";
import { Icon } from "@iconify/react/dist/iconify.js";
import { useEffect, useState } from "react";
import client from "../../../../Auth";
import dayjs from "dayjs";
import { useParams, useRouter } from "next/navigation";
import { formatTime } from "../../../../utils/CommonFunction";
import { gradientClasses } from "@utils/constant.utils";

const CreateDateReservationTableMainComponent = () => {
    const router = useRouter()

    // const params = useParams();
    // const restaurantbranch = params?.restaurantbranch;
    // const RestaruntBranch = restaurantbranch
    const [formData, setFormData] = useState({
        from_date: "",
        to_date: "",
        start_time: "",
        end_time: "",
        interval: "",
    });
    const [slots, setSlots] = useState([]);
    const [errors, setErrors] = useState({});
    const [dateList, setDateList] = useState([]);
    const [selectedDate, setSelectedDate] = useState(null);
    const [localConfigs, setLocalConfigs] = useState({});
    const [restaruntBranch, setRestaruntBranch] = useState("")

    useEffect(() => {
        const restarunt = localStorage.getItem("restaurantbranch")
        setRestaruntBranch(restarunt)
    }, [])


    useEffect(() => {
        const isLogin = JSON.parse(localStorage.getItem("isLogin"));
        if (!isLogin) {
            router.push(`/admin?restaurantbranch=${restaruntBranch}`);
        }
    }, [router]);

    const GetData = async (date) => {
        const dayName = dayjs(date).format('dddd');
        const [dayid, enabledTables] = await getTableData(dayName) || [];

        const enriched = enabledTables.map(cfg => ({
            ...cfg,
            date,
            day: dayName,
            dayid: dayid,
            table: cfg.name,
            start_time: formData.start_time,
            end_time: formData.end_time,
            interval: formData.interval,
            tablename: cfg.table
        }));


        setLocalConfigs(prev => ({
            ...prev,
            [date]: enriched
        }));
    }

    const onDateSelected = async (date) => {
        setSelectedDate(date);

        if (localConfigs[date]) {
            return;
        }
        GetData(date)

    };

    const getTableData = async (Day) => {
        console.log(Day)
        try {

            // fetch the “Days” doc for this Day name
            // const dayResp = await client.get(
            //     `/Dine360%20Days?filters=[["day","=","${Day}"]]&fields=["*"]`
            // );

            const dayResp = await client.get(
                `/Dine360%20Days?filters=[["day","=","${Day}"]  ,["restaurantbranch","=","${restaruntBranch}"]]&fields=["*"]  `
            );

            const dayDoc = dayResp.data.data[0];
            const dayNameKey = dayDoc?.name;

            // fetch all tables + that day’s configuration
            const [tableRes, dayConfigRes] = await Promise.all([
                // client.get(`/Dine360%20Table?fields=["*"]`),
                client.get(`/Dine360%20Table?fields=["*"]&filters=[["restaurantbranch","=","${restaruntBranch}"]]`),

                client.get(`/Dine360%20Days/${dayNameKey}`)
            ]);

            const enabledTables = dayConfigRes.data.data.table_configuration || [];

            console.log(dayConfigRes.data.data)
            // store in your existing state if you like
            // setTableConfigs(enabledTables);

            // optional: merge with all tables to show which ones exist
            const allTables = tableRes.data.data;

            const enabledNames = new Set(enabledTables.map(t => t.table));

            const alltableswithselections = allTables.map(tbl => ({
                ...tbl,
                enabled: enabledNames.has(tbl.name)
            }))

            console.log("111111111", alltableswithselections)
            // setTables();

            return [dayNameKey, alltableswithselections];
        } catch (err) {
            console.error("Error fetching table data:", err);
            return [];   // ensure we never return undefined
        }
    };



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

    const generateSlots = () => {
        const newErrors = {};
        if (!formData.from_date) newErrors.from_date = "From date is required";
        if (!formData.to_date) newErrors.to_date = "To date is required";
        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)) {
            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 from = dayjs(formData.from_date);
        const to = dayjs(formData.to_date);
        const dates = [];
        let cursor = from;
        while (cursor.isBefore(to) || cursor.isSame(to)) {

            GetData(cursor.format("YYYY-MM-DD"))

            dates.push(cursor.format("YYYY-MM-DD"));
            cursor = cursor.add(1, "day");
        }
        setDateList(dates);
        setSelectedDate(dates[0] || null);

    };


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

    const handleSubmit = async (e) => {
        e.preventDefault();
        const newErrors = {};
        if (!formData.from_date) newErrors.from_date = "From date is required";
        if (!formData.to_date) newErrors.to_date = "To date is required";
        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 allTablesConfigs = Object.values(localConfigs).flatMap(dateArray => dateArray);
        const payload = {
            ...formData,
            interval: Number(formData.interval),
            restaurantbranch: restaruntBranch,
            slots: slots.map((slot) => ({
                ...slot,
                enabled: slot.enabled ? 1 : 0,
            })),
            table_configurations: allTablesConfigs
        };

        try {
            // if (editMode) {
            //     await client.put(`/Dine360%20Table%20Reservation%20Master/${editingId}`, payload);
            // } else {
            await client.post("/Dine360%20Table%20Reservation%20Master", payload);
            // }

            setErrors({});
            setFormData({
                from_date: "",
                to_date: "",
                start_time: "",
                end_time: "",
                interval: "",
            });
            setSlots([]);
            router?.push(`/admin/date-reservation-table?restaurantbranch=${restaruntBranch}`)
        } catch (error) {
            console.log("Submit error:", error);
        }
    };






    // const onDateSelected = async (date) => {
    //     setSelectedDate(date);

    //     // if we've already loaded configs for this date, skip refetch
    //     if (localConfigs[date]) {
    //         return;
    //     }

    //     const dayName = dayjs(date).format('dddd');
    //     // fetch the enabled tables for that day
    //     const enabledTables = await getTableData(dayName); // ensure getTableData returns the array
    //     console.log(enabledTables)
    //     // enrich each config
    //     const enriched = enabledTables.map(cfg => ({
    //         ...cfg,
    //         date,                // the selected date
    //         day: dayName,        // e.g. "Tuesday"
    //         dayid: cfg.name,     // or cfg.parent if that's the unique key from Frappe
    //     }));

    //     setLocalConfigs(prev => ({
    //         ...prev,
    //         [date]: enriched
    //     }));
    // };





    console.log("slot", slots)
    return (
        <>
            <div className="container-fluid" style={{ marginBottom: "100px" }}>

                <div className="row justify-content-center">
                    <div className="col-xxl-8 col-xl-8 col-lg-10">
                        <div className="card">
                            <div className="card-body p-3 p-lg-5">
                                <h6 className="text-lg text-primary-light mb-16">
                                    Create Date reservation
                                </h6>

                                <form onSubmit={handleSubmit}>
                                    <div className="row">
                                        <div className="col-6 mb-3">
                                            <label className="form-label">From Date</label>
                                            <input type="date" className={`form-control ${errors.from_date ? 'is-invalid' : ''}`} name="from_date" value={formData.from_date} onChange={handleChange} />
                                            {errors.from_date && <div className="invalid-feedback">{errors.from_date}</div>}
                                        </div>
                                        <div className="col-6 mb-3">
                                            <label className="form-label">To Date</label>
                                            <input type="date" className={`form-control ${errors.to_date ? 'is-invalid' : ''}`} name="to_date" value={formData.to_date} onChange={handleChange} />
                                            {errors.to_date && <div className="invalid-feedback">{errors.to_date}</div>}
                                        </div>
                                    </div>
                                    <div className="row">
                                        <div className="col-6 mb-3">
                                            <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} />
                                            {errors.start_time && <div className="invalid-feedback">{errors.start_time}</div>}
                                        </div>
                                        <div className="col-6 mb-3">
                                            <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} />
                                            {errors.end_time && <div className="invalid-feedback">{errors.end_time}</div>}
                                        </div>
                                    </div>

                                    <div className="mb-3">
                                        <label className="form-label">Interval (minutes)</label>
                                        <input type="number" className={`form-control ${errors.interval ? 'is-invalid' : ''}`} name="interval" value={formData.interval} onChange={handleChange} />
                                        {errors.interval && <div className="invalid-feedback">{errors.interval}</div>}
                                    </div>
                                    <button type="button" className="btn btn-bg-theme radius-8 px-14 py-6 text-sm mb-3" onClick={generateSlots}>Generate Slots</button>

                                    {slots.length > 0 && (
                                        <div className="border p-3 rounded">
                                            <h6 className="text-md">Generated Slots:</h6>
                                            <div className="d-flex flex-wrap gap-2">
                                                {slots.map((slot, index) => (
                                                    <div key={index}>
                                                        <input
                                                            type="checkbox"
                                                            className="btn-check"
                                                            id={`slot-${index}`}
                                                            autoComplete="off"
                                                            checked={slot.enabled}
                                                            onChange={() => handleSlotToggle(index)}
                                                        />
                                                        <label
                                                            className="btn btn-outline-success"
                                                            htmlFor={`slot-${index}`}
                                                            style={{ minWidth: "80px" }}
                                                        >
                                                            {formatTime(slot.slot_time)}
                                                        </label>
                                                    </div>
                                                ))}
                                            </div>
                                        </div>
                                    )}

                                    <div className={`${selectedDate && "border"}  p-3 rounded mt-3`}>
                                        {dateList.length > 0 && (
                                            <div >
                                                <h6 className="text-md">Select a Date:</h6>
                                                <div className="d-flex flex-wrap gap-2 mb-3">
                                                    {dateList.map((date, index) => {
                                                        const gradientClass = gradientClasses[index % gradientClasses.length];
                                                        return (
                                                            <button
                                                                key={date}
                                                                type="button"
                                                                className={`btn px-14 py-6 text-sm ${selectedDate === date ? 'btn-bg-theme text-white' : 'btn-outline-theme'}`}
                                                                onClick={() => { onDateSelected(date) }
                                                                }
                                                            >
                                                                {dayjs(date).format('dddd, MMM D')}

                                                            </button>
                                                        )
                                                    }

                                                    )}
                                                </div>
                                            </div>
                                        )}

                                        {selectedDate && localConfigs[selectedDate] && (
                                            <div className="mt-3">
                                                <h6 className="text-md mb-3">
                                                    Tables for {dayjs(selectedDate).format('dddd, MMM D')}
                                                </h6>
                                                <div className="row g-3">
                                                    {localConfigs[selectedDate]
                                                        .filter(cfg => cfg.day === dayjs(selectedDate).format('dddd'))
                                                        .map((cfg, index) => {
                                                            const gradientClass = gradientClasses[index % gradientClasses.length];
                                                            return (
                                                                <div className="col-12 col-md-6 col-lg-4" key={cfg.name}>
                                                                    <div className={`card p-3 bg-theme`}>
                                                                        <h6 className="card-title">{cfg.table}</h6>

                                                                        <div className="d-flex flex-column gap-0 mb-3">
                                                                            <div className="mb-0">
                                                                                <span className="text-sm"><strong>Start:</strong> {cfg.start_time}</span>
                                                                                {" - "}
                                                                                <span className="text-sm"><strong>End:</strong> {cfg.end_time}</span>
                                                                            </div>
                                                                            <div>
                                                                                <strong className="text-sm">Interval:</strong> {cfg.interval} mins
                                                                            </div>
                                                                        </div>

                                                                        <button type="button"
                                                                            className={`btn ${cfg.enabled ? "btn-success" : "btn-outline-danger"} btn-sm`}
                                                                            onClick={() => {
                                                                                setLocalConfigs(prev => {
                                                                                    const updated = prev[selectedDate].map(item =>
                                                                                        item.name === cfg.name
                                                                                            ? { ...item, enabled: item.enabled ? 0 : 1 }
                                                                                            : item
                                                                                    );
                                                                                    return { ...prev, [selectedDate]: updated };
                                                                                });
                                                                            }}
                                                                        >
                                                                            {cfg.enabled ? "Enabled" : "Click to Enable"}
                                                                        </button>
                                                                    </div>

                                                                </div>
                                                            )
                                                        })}
                                                </div>
                                            </div>
                                        )}
                                    </div>

                                    <div className="mt-3 d-flex justify-content-end">
                                        <button type="submit" className="btn btn-bg-theme">
                                            Create Reservation
                                        </button>
                                    </div>

                                </form>
                            </div>
                        </div>
                    </div>
                </div>

            </div>
        </>
    );
};

export default CreateDateReservationTableMainComponent;
