"use client"
import React, { useState } from "react";
import classNames from "classnames";
import { Icon } from "@iconify/react";

const DineList = () => {
    // Get current date and time
    const getCurrentDateTime = () => {
        const now = new Date();
        const date = now.toISOString().split('T')[0]; // YYYY-MM-DD
        const time = now.toTimeString().slice(0, 5); // HH:mm
        return { date, time };
    };

    const { date: currentDate, time: currentTime } = getCurrentDateTime();

    const [floors, setFloors] = useState([
        {
            id: 1,
            name: "Ground Floor",
            tables: [
                { id: 1, number: 1, name: "Table 1", seats: 4, bookings: [{ date: "2025-05-13", time: "18:00" }] },
                { id: 2, number: 2, name: "Table 2", seats: 2, bookings: [] },
                { id: 3, number: 3, name: "Table 3", seats: 6, bookings: [] },
            ]
        },
        {
            id: 2,
            name: "First Floor",
            tables: [
                { id: 4, number: 4, name: "Table 4", seats: 4, bookings: [] },
                { id: 5, number: 5, name: "Table 5", seats: 8, bookings: [] },
            ]
        }
    ]);

    const [selectedDate, setSelectedDate] = useState(currentDate);
    const [selectedTime, setSelectedTime] = useState(currentTime);
    const [selectedFloor, setSelectedFloor] = useState(1);
    const [showAddTableModal, setShowAddTableModal] = useState(false);
    const [newTable, setNewTable] = useState({
        number: "",
        name: "",
        seats: 2
    });

    const isTableBooked = (table, date, time) =>
        table.bookings.some((b) => b.date === date && b.time === time);

    const handleAddTable = () => {
        const updatedFloors = floors.map(floor => {
            if (floor.id === selectedFloor) {
                return {
                    ...floor,
                    tables: [...floor.tables, {
                        id: Date.now(),
                        number: floor.tables.length + 1,
                        name: newTable.name || `Table ${floor.tables.length + 1}`,
                        seats: parseInt(newTable.seats),
                        bookings: []
                    }]
                };
            }
            return floor;
        });
        setFloors(updatedFloors);
        setShowAddTableModal(false);
        setNewTable({ number: "", name: "", seats: 2 });
    };

    const handleDeleteTable = (tableId) => {
        if (window.confirm("Are you sure you want to delete this table?")) {
            const updatedFloors = floors.map(floor => {
                if (floor.id === selectedFloor) {
                    return {
                        ...floor,
                        tables: floor.tables.filter(table => table.id !== tableId)
                    };
                }
                return floor;
            });
            setFloors(updatedFloors);
        }
    };

    return (
        <div className="container">
            {/* Header Section with Floor Tabs, Date/Time, and Add Button */}
            <div className="card mb-3">
                <div className="card-body p-3">
                    <div className="d-flex align-items-stretch gap-3">
                        {/* Floor Tabs */}
                        <div className="nav nav-tabs border-0 flex-grow-1 d-flex align-items-center" role="tablist">
                            {floors.map((floor) => (
                                <button
                                    key={floor.id}
                                    className={classNames(
                                        'nav-link border-0 me-1 h-100 d-flex align-items-center px-3',
                                        {
                                            'active bg-primary text-white': floor.id === selectedFloor,
                                            '#4b5563': floor.id !== selectedFloor
                                        }
                                    )}
                                    onClick={() => setSelectedFloor(floor.id)}
                                >
                                    {floor.name}
                                </button>
                            ))}
                        </div>

                        {/* Date & Time Inputs */}
                        <div className="d-flex gap-2 align-items-stretch">
                            <div className="input-group h-100">
                                {/* <span className="input-group-text border-0 d-flex align-items-center ">
                                    <Icon icon="mdi:calendar" />
                                </span> */}
                                <input
                                    type="date"
                                    value={selectedDate}
                                    onChange={(e) => setSelectedDate(e.target.value)}
                                    className="form-control border-0  h-100"
                                />
                            </div>
                            <div className="input-group h-100">
                                {/* <span className="input-group-text border-0 d-flex align-items-center">
                                    <Icon icon="mdi:clock" />
                                </span> */}
                                <input
                                    type="time"
                                    value={selectedTime}
                                    onChange={(e) => setSelectedTime(e.target.value)}
                                    className="form-control border-0 h-100"
                                />
                            </div>
                        </div>

                        {/* Add Table Button */}
                        <button
                            className="btn btn-primary px-4 d-flex align-items-center"
                            onClick={() => setShowAddTableModal(true)}
                        >
                            Add Table
                        </button>
                    </div>
                </div>
            </div>

            {/* Tables Grid */}
            <div className='row gy-4 gx-4 justify-content-center pb-3'>
                {floors.find(f => f.id === selectedFloor)?.tables.map((table) => {
                    const isBooked = isTableBooked(table, selectedDate, selectedTime);

                    return (
                        <div key={table.id} className='col-xxl-4 col-lg-4 col-sm-6'>
                            <div
                                className={classNames(
                                    'card p-3 shadow-2 radius-8 h-100 border border-white position-relative overflow-hidden',
                                    {
                                        'hover-card': !isBooked,
                                        'opacity-75': isBooked,
                                    }
                                )}
                            >
                                <div className='card-body text-center p-0'>
                                    <div className="d-flex justify-content-between align-items-center mb-3">
                                        <h6 className='fw-semibold mt-3'>{table.name}</h6>
                                        <Icon 
                                            icon="mdi:delete" 
                                            className="text-danger cursor-pointer"
                                            style={{ fontSize: '1.5rem' }}
                                            onClick={() => handleDeleteTable(table.id)}
                                        />
                                    </div>
                                    <div className='d-flex flex-wrap align-items-center justify-content-center gap-1 mb-8 position-relative'>
                                        <span className='mb-0 w-200-px h-200-px position-relative'>
                                            <img
                                                src='/assets/images/dine-in/restarunt-table.webp'
                                                alt=''
                                                className={classNames(
                                                    'mx-auto d-block w-100 h-100 object-fit-cover',
                                                    { 'grayscale': isBooked }
                                                )}
                                            />
                                            {!isBooked ? (
                                                <div className="hover-overlay d-flex justify-content-center align-items-center cursor-pointer">
                                                    <span className="hover-icon display-1 text-white">+</span>
                                                </div>
                                            ) : (
                                                <div className="position-absolute top-50 start-50 translate-middle text-white bg-danger px-3 py-1 rounded">
                                                    Booked
                                                </div>
                                            )}
                                        </span>
                                    </div>
                                    <div className="d-flex align-items-center justify-content-center">
                                        <Icon icon="mdi:chair" className="me-2" />
                                        <span>{table.seats} Seats</span>
                                    </div>
                                </div>
                            </div>
                        </div>
                    );
                })}
            </div>

            {/* Add Table Modal with Overlay */}
            {showAddTableModal && (
                <>
                    <div 
                        className="modal-backdrop fade show" 
                        style={{ 
                            position: 'fixed',
                            top: 0,
                            left: 0,
                            right: 0,
                            bottom: 0,
                            backgroundColor: 'rgba(0, 0, 0, 0.5)',
                            zIndex: 1040
                        }}
                        onClick={() => setShowAddTableModal(false)}
                    />
                    <div 
                        className="modal fade show" 
                        style={{ 
                            display: 'block',
                            zIndex: 1050
                        }}
                    >
                        <div className="modal-dialog modal-dialog-centered">
                            <div className="modal-content shadow-lg">
                                <div className="modal-header border-0">
                                    <h6 className="modal-title">Add New Table</h6>
                                    <button
                                        type="button"
                                        className="btn-close"
                                        onClick={() => setShowAddTableModal(false)}
                                    ></button>
                                </div>
                                <div className="modal-body">
                                    <div className="mb-3">
                                        <label className="form-label">Table Name</label>
                                        <input
                                            type="text"
                                            className="form-control"
                                            placeholder="Enter table name"
                                            value={newTable.name}
                                            onChange={(e) => setNewTable({ ...newTable, name: e.target.value })}
                                        />
                                    </div>
                                    <div className="mb-3">
                                        <label className="form-label">Number of Seats</label>
                                        <input
                                            type="number"
                                            className="form-control"
                                            min="1"
                                            value={newTable.seats}
                                            onChange={(e) => setNewTable({ ...newTable, seats: e.target.value })}
                                        />
                                    </div>
                                </div>
                                <div className="modal-footer border-0">
                                    <button
                                        type="button"
                                        className="btn btn-light"
                                        onClick={() => setShowAddTableModal(false)}
                                    >
                                        Cancel
                                    </button>
                                    <button
                                        type="button"
                                        className="btn btn-primary"
                                        onClick={handleAddTable}
                                    >
                                        Add Table
                                    </button>
                                </div>
                            </div>
                        </div>
                    </div>
                </>
            )}
        </div>
    );
};

export default DineList;
