'use client'
import React, { Suspense, useEffect, useState } from "react";
import client from "@auth";
import PageLoader from "@/components/common-component/PageLoader";
import PageNoData from "@/components/common-component/PageNoData";
import classNames from "classnames";
import { useRouter, useSearchParams } from "next/navigation";

const DayReservationTableEnableInner = () => {
    const router = useRouter();

    // const day_name = params.name;
    const searchParams = useSearchParams();
    const day = searchParams.get('day');
    const day_name = searchParams.get('name');

    const [tables, setTables] = useState([]);
    const [showModal, setShowModal] = useState(false);
    const [selectedTable, setSelectedTable] = useState(null);
    const [error, setError] = useState('');
    const [tableConfigs, setTableConfigs] = useState([]);
    const [errors, setErrors] = useState({});
    const [loading, setLoading] = useState(true);

    const [formData, setFormData] = useState({
        enabled: false,
        start_time: '',
        end_time: '',
        interval: ''
    });
    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]);



    useEffect(() => {
        if (restaruntBranch && restaruntBranch !== "")
            getTableData();
    }, [restaruntBranch]);


    const getTableData = async () => {
        try {
            setLoading(true)
            const [tableRes, enableTableRes] = await Promise.all([
                // client.get(`/Dine360%20Table?fields=["*"]`),
                client.get(`/Dine360%20Table?fields=["*"]&filters=[["restaurantbranch","=","${restaruntBranch}"]]`),
                client.get(`/Dine360%20Days/${day_name}?fields=["*"]`)
            ]);

            const allTables = tableRes.data.data || [];
            const enabledTables = enableTableRes.data.data?.table_configuration || [];

            setTableConfigs(enabledTables);

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

            const mergedTables = allTables.map((table) => ({
                ...table,
                enabled: enabledNames.has(table.name)
            }));

            setTables(mergedTables);
            setLoading(false)
        } catch (error) {
            console.error("Error fetching table or enabled list:", error);
            setLoading(false)
        }
    };
    console.log("tableConfigs", tableConfigs)

    const formatTime = (timeStr) => {
        if (!timeStr) return '';
        const parts = timeStr.split(':');
        return parts.length >= 2 ? `${parts[0].padStart(2, '0')}:${parts[1].padStart(2, '0')}` : '';
    };

    const handleTableClick = (table) => {
        setSelectedTable(table);
        setError('');

        const existingConfig = tableConfigs.find(cfg => cfg.table === table.name);
        if (existingConfig) {
            setFormData({
                enabled: true,
                start_time: formatTime(existingConfig.start_time),
                end_time: formatTime(existingConfig.end_time),
                interval: existingConfig.interval?.toString() || ''
            });
        } else {
            setFormData({
                enabled: false,
                start_time: '',
                end_time: '',
                interval: ''
            });
        }

        setShowModal(true);
    };

    const handleChange = (e) => {
        const { name, value, type, checked } = e.target;
        setFormData((prev) => ({
            ...prev,
            [name]: type === 'checkbox' ? checked : value
        }));
    };

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

        const newErrors = {};

        if (!formData.enabled) {
            // Remove any config for this table when disabling
            setTableConfigs(prev => prev.filter(cfg => cfg.table !== selectedTable?.name));
            setShowModal(false);
            return;
        }

        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) {
            newErrors.interval = 'Interval is required.';
        } else if (isNaN(formData.interval) || formData.interval <= 0) {
            newErrors.interval = 'Interval must be a positive number.';
        }

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

        const formatTime = (timeStr) => {
            if (!timeStr) return '';
            const [hour, minute] = timeStr.split(':');
            const hh = hour.padStart(2, '0');
            const mm = minute.padStart(2, '0');
            return `${hh}:${mm}:00`;
        };

        const newConfig = {
            day,
            table: selectedTable?.name,
            enabled: 1,
            start_time: formatTime(formData.start_time),
            end_time: formatTime(formData.end_time),
            interval: Number(formData.interval)
        };

        // Replace or add only enabled configs
        setTableConfigs(prevConfigs => {
            const filtered = prevConfigs.filter(cfg => cfg.table !== newConfig.table);
            return [...filtered, newConfig];
        });

        setShowModal(false);
        setErrors({});
        setFormData({ enabled: false, start_time: '', end_time: '', interval: '' });
    };


    const handleModelClose = () => {
        setShowModal(false);
        setErrors({});
        setFormData({ enabled: false, start_time: '', end_time: '', interval: '' });
    };

    const handleSaveAllChanges = async () => {
        if (tableConfigs.length === 0) {
            alert("No changes to save.");
            return;
        }

        const confirmed = window.confirm("Are you sure you want to save all changes?");
        if (!confirmed) return;

        const payload = {
            name: day_name,
            table_configuration: tableConfigs
        };

        try {
            await client.put(`/Dine360%20Days/${day_name}`, payload, {
                headers: { 'Content-Type': 'application/json' }
            });
            alert("All table configurations saved successfully!");
            setTableConfigs([]);
            getTableData();
        } catch (error) {
            console.error("Error saving all changes:", error);
            alert("Failed to save configurations.");
        }
    };

    const sortedTables = [...tables].sort((a, b) => a.tablename.localeCompare(b.tablename));
    console.log("sortedTables", sortedTables)
    return (
        <>

            {loading ? (
                <PageLoader />
            ) : sortedTables?.lenght === 0 ? (
                <PageNoData />
            ) : (
                <>
                    <div className="container-fluid" style={{ marginBottom: "100px" }}>
                        <div className='card h-100 p-0 radius-12'>
                            <div className='card-body p-3 p-lg-5 p-lg-40'>
                                <div className="d-flex justify-content-between mb-5">
                                    <div className="d-flex align-items-center">
                                        <h6 className="text-lg mb-0">
                                            Day Reservations
                                        </h6>
                                    </div>
                                    <button
                                        type="button"
                                        className="btn btn-bg-theme radius-8 px-16 py-7"
                                        onClick={handleSaveAllChanges}
                                    >
                                        Save All Changes
                                    </button>
                                </div>

                                <div className='row gy-3 gx-3 gx-lg-5 gy-lg-5 justify-content-center'>
                                    {sortedTables.map((table) => (
                                        <div className="col-xxl-2 col-lg-3 col-md-4 col-sm-6 col-6 text-center" key={table.name}>
                                            <div className="d-inline-block">
                                                <div
                                                    className={` cursor-pointer p-3  radius-12 ${table.enabled ? 'bg-success-focus' : 'bg-theme'} `}
                                                    onClick={() => handleTableClick(table)}
                                                >
                                                    <div className="text-center p-0 position-relative">
                                                        <h6 className="text-lg mt-0 mb-1">{table?.tablename}</h6>
                                                        <span className='mb-0 w-100-px h-100-px position-relative'>
                                                            {
                                                                table?.totalcapacity <= 2 ? (
                                                                    <img
                                                                        src='/assets/images/seat/seating-02.png'
                                                                        alt=''
                                                                        className={classNames(
                                                                            'mx-auto d-block w-100 h-100 object-fit-cover',
                                                                            { 'grayscale': table.status === 'booked' }
                                                                        )}
                                                                    />
                                                                ) : table?.totalcapacity <= 4 ? (
                                                                    <img
                                                                        src='/assets/images/seat/seating-04.png'
                                                                        alt=''
                                                                        className={classNames(
                                                                            'mx-auto d-block w-100 h-100 object-fit-cover',
                                                                            { 'grayscale': table.status === 'booked' }
                                                                        )}
                                                                    />
                                                                ) : table?.totalcapacity <= 6 ? (
                                                                    <img
                                                                        src='/assets/images/seat/seating-06.png'
                                                                        alt=''
                                                                        className={classNames(
                                                                            'mx-auto d-block w-100 h-100 object-fit-cover',
                                                                            { 'grayscale': table.status === 'booked' }
                                                                        )}
                                                                    />
                                                                ) : table?.totalcapacity <= 8 ? (
                                                                    <img
                                                                        src='/assets/images/seat/seating-08.png'
                                                                        alt=''
                                                                        className={classNames(
                                                                            'mx-auto d-block w-100 h-100 object-fit-cover',
                                                                            { 'grayscale': table.status === 'booked' }
                                                                        )}
                                                                    />
                                                                ) : table?.totalcapacity <= 10 && (
                                                                    <img
                                                                        src='/assets/images/seat/seating-10.png'
                                                                        alt=''
                                                                        className={classNames(
                                                                            'mx-auto d-block w-100 h-100 object-fit-cover',
                                                                            { 'grayscale': table.status === 'booked' }
                                                                        )}
                                                                    />
                                                                )
                                                            }


                                                        </span>

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


                            </div>

                            {showModal && (
                                <div className="modal fade show" style={{ display: 'block', backgroundColor: 'rgba(0,0,0,0.5)' }}>
                                    <div className="modal-dialog modal-dialog-centered">
                                        <div className="modal-content">
                                            <div className="modal-header border-0 pb-0">
                                                <h6 className="modal-title fs-5">Enable Table - {selectedTable?.tablename}</h6>
                                                <button type="button" className="btn-close" onClick={handleModelClose}></button>
                                            </div>

                                            <div className="modal-body">
                                                <div className="mb-3">
                                                    <div className="d-flex align-items-center" style={{ gap: '5px' }}>
                                                        <input
                                                            type="checkbox"
                                                            className="form-check-input mt-0"
                                                            id="enableTableCheck"
                                                            name="enabled"
                                                            checked={formData.enabled}
                                                            onChange={handleChange}
                                                        />
                                                        <label className="form-check-label" htmlFor="enableTableCheck">
                                                            Enable Table
                                                        </label>
                                                    </div>
                                                </div>
                                                {formData.enabled && (
                                                    <>
                                                        <div className="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="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 className="mb-3">
                                                            <label className="form-label">Interval (in minutes)</label>
                                                            <input
                                                                type="number"
                                                                className={`form-control ${errors.interval ? 'is-invalid' : ''}`}
                                                                name="interval"
                                                                value={formData.interval}
                                                                min="1"
                                                                onChange={handleChange}
                                                            />
                                                            {errors.interval && <div className="invalid-feedback">{errors.interval}</div>}
                                                        </div>
                                                    </>
                                                )}
                                            </div>

                                            <div className="modal-footer border-0 pt-0">
                                                <button type="button" className="btn btn-sm btn-outline-danger" onClick={handleModelClose}>Cancel</button>
                                                <button type="button" className="btn btn-sm btn-danger-500" onClick={handleSubmit}>Save</button>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            )}
                        </div>
                    </div>
                </>)}
        </>
    );
};
const DayReservationTableEnable = (() => {
    return (
        <Suspense fallback={<PageLoader />}>
            <DayReservationTableEnableInner />
        </Suspense>
    )
})
export default DayReservationTableEnable;
