'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 searchParams = useSearchParams();
    const day = searchParams.get('day');
    const day_name = searchParams.get('name');

    const [tables, setTables] = useState([]);
    const [tableConfigs, setTableConfigs] = useState([]);
    const [selectedTable, setSelectedTable] = useState(null);
    const [showModal, setShowModal] = useState(false);
    const [formData, setFormData] = useState({ enabled: false, start_time: '', end_time: '', interval: '' });
    const [errors, setErrors] = useState({});
    const [restaurantBranch, setRestaurantBranch] = useState('');
    const [loading, setLoading] = useState(true);

    useEffect(() => {
        const branch = localStorage.getItem('restaurantbranch');
        setRestaurantBranch(branch);
    }, []);

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

    useEffect(() => {
        if (restaurantBranch) getTableData();
    }, [restaurantBranch]);

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

            const allTables = tableRes.data.data || [];
            const savedConfigs = configRes.data.data?.table_configuration || [];

            setTableConfigs(savedConfigs);

            const enabledNames = new Set(savedConfigs.filter(t => t.enabled).map(t => t.table));

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

            setTables(merged);
            setLoading(false);
        } catch (error) {
            console.error('Error loading table data:', error);
            setLoading(false);
        }
    };

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

        const existing = tableConfigs.find(cfg => cfg.table === table.name);

        if (existing && existing.enabled) {
            setFormData({
                enabled: true,
                start_time: existing.start_time?.slice(0, 5) || '',
                end_time: existing.end_time?.slice(0, 5) || '',
                interval: existing.interval?.toString() || ''
            });
        } else {
            setFormData({
                enabled: false,
                start_time: '',
                end_time: '',
                interval: ''
            });
        }

        setShowModal(true);
        setErrors({});
    };


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

    const handleSubmit = () => {
        const errs = {};
        if (formData.enabled) {
            if (!formData.start_time) errs.start_time = 'Start time required';
            if (!formData.end_time) errs.end_time = 'End time required';
            if (!formData.interval || isNaN(formData.interval) || formData.interval <= 0) {
                errs.interval = 'Positive interval required';
            }
        }

        if (Object.keys(errs).length > 0) {
            setErrors(errs);
            return;
        }

        const updatedConfig = formData.enabled
            ? {
                day,
                table: selectedTable.name,
                enabled: 1,
                start_time: `${formData.start_time}:00`,
                end_time: `${formData.end_time}:00`,
                interval: Number(formData.interval)
            }
            : {
                day,
                table: selectedTable.name,
                enabled: 0,
                start_time: null,
                end_time: null,
                interval: null
            };

        setTableConfigs(prev => {
            const others = prev.filter(cfg => cfg.table !== selectedTable.name);
            return [...others, updatedConfig];
        });

        setShowModal(false);
    };

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

    const handleSaveAllChanges = async () => {
        const confirm = window.confirm('Are you sure you want to save all changes?');
        if (!confirm) return;

        const fullConfigs = tables.map(table => {
            const cfg = tableConfigs.find(c => c.table === table.name);
            return cfg
                ? cfg
                : {
                    day,
                    table: table.name,
                    enabled: 0,
                    start_time: null,
                    end_time: null,
                    interval: null
                };
        });

        try {
            await client.put(`/Dine360%20Days/${day_name}`, {
                name: day_name,
                table_configuration: fullConfigs
            }, {
                headers: { 'Content-Type': 'application/json' }
            });
            alert('Saved successfully!');
            setTableConfigs([]);
            getTableData();
        } catch (error) {
            console.error('Save failed:', error);
            alert('Failed to save changes.');
        }
    };

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

            {loading ? (
                <PageLoader />
            ) : sortedTables?.lenght === 0 ? (
                <PageNoData />
            ) : (
                <>
                    <div className="container" style={{ marginBottom: "100px" }}>
                        <div className=' h-100 p-0 radius-12'>
                            <div className='p-3 '>
                                <div className="d-flex justify-content-end mb-3">
                                    {/* <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 radius-12"
                                                    onClick={() => handleTableClick(table)}
                                                >
                                                    <div
                                                        className={`position-relative d-inline-block p-2 radius-12`}
                                                        style={{ width: "150px" }}
                                                    >
                                                        {/* Table Image */}
                                                        <img
                                                            src={
                                                                table.totalcapacity <= 2
                                                                    ? '/assets/images/seat/seating-24.png'
                                                                    : table.totalcapacity <= 4
                                                                        ? '/assets/images/seat/seating-25.png'
                                                                        : table.totalcapacity <= 6
                                                                            ? '/assets/images/seat/seating-26.png'
                                                                            : table.totalcapacity <= 8
                                                                                ? '/assets/images/seat/seating-27.png'
                                                                                : '/assets/images/seat/seating-28.png'
                                                            }
                                                            alt=""
                                                            className={classNames(
                                                                'w-100 h-100 object-fit-cover',
                                                                { grayscale: table.status === 'booked' }
                                                            )}
                                                        />

                                                        {/* Table name overlay at center */}
                                                        <div className={`position-absolute top-50 start-50 translate-middle text-white  ${table.enabled ? 'bg-success-500' : 'bg-theme'
                                                            } fw-bold`}>
                                                            <h6
                                                                className={`position-absolute text-xs translate-middle text-white fw-bold text-center d-flex align-items-center justify-content-center ${table.enabled ? "bg-success-500" : "bg-warning-500"}`}
                                                                style={{
                                                                    pointerEvents: "none",
                                                                    top: "55%",
                                                                    left: "50%",
                                                                    width: "50px",
                                                                    height: "50px",
                                                                    borderRadius: "50%",

                                                                }}
                                                            >{table.tablename}
                                                            </h6>
                                                        </div>
                                                    </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;
