"use client";

import { useEffect, useState } from "react";
import client from "@auth";
import dayjs from "dayjs";
import PageLoader from "../common-component/PageLoader";
import PageNoData from "../common-component/PageNoData";
import { useRouter } from "next/navigation";
import { exportReservationToExcel, formatTime, statusStyles } from "@utils/CommonFunction";
import Link from "next/link";
import { Icon } from "@iconify/react";

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

    const [allReservations, setAllReservations] = useState([]);
    const [dateReservation, setDateReservation] = useState([]);
    const [loading, setLoading] = useState(true);
    const [deleteConfirm, setDeleteConfirm] = useState({ show: false, id: null });
    const [restaruntBranch, setRestaruntBranch] = useState("");
    const [selectedStatus, setSelectedStatus] = useState("");

    const [fromDate, setFromDate] = useState("");
    const [toDate, setToDate] = 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 !== "") {
            getReservationDate();
        }
    }, [restaruntBranch]);

    const getReservationDate = async () => {
        try {
            setLoading(true);
            const res = await client.get(
                `/Dine360%20Reservation?fields=["*"]&filters=[["restaurantbranch","=","${restaruntBranch}"]]`
            );
            const data = res?.data?.data || [];
            setAllReservations(data);
            setDateReservation(data);
            setLoading(false);
        } catch (error) {
            console.error("Fetch error:", error);
            setLoading(false);
        }
    };

    const applyDateFilter = () => {
        let filtered = allReservations;

        if (fromDate) {
            const from = new Date(fromDate);
            filtered = filtered.filter(item => new Date(item.reservation_date) >= from);
        }

        if (toDate) {
            const to = new Date(toDate);
            filtered = filtered.filter(item => new Date(item.reservation_date) <= to);
        }

        setDateReservation(filtered);
    };

    const handleCreateDateReservation = () => {
        router.push(`/admin/create-user-table-reservation?restaurantbranch=${restaruntBranch}`);
    };

    const handleEditModel = (reservation) => {
        router.push(`/admin/update-user-table-reservation?restaurantbranch=${restaruntBranch}&name=${reservation?.name}`);
    };

    const handleStatusUpdate = async () => {
        if (!selectedStatus) {
            alert("Please select a status");
            return;
        }

        try {
            await client.put(`/Dine360%20Reservation/${deleteConfirm.id}`, {
                status: selectedStatus,
            });
            setDeleteConfirm({ show: false, id: null });
            setSelectedStatus("");
            getReservationDate();
        } catch (error) {
            console.error("Error updating status:", error);
            alert("Failed to update reservation status.");
        }
    };

    const handleExport = () => {
        exportReservationToExcel(dateReservation);
    };

    return (
        <>
            {loading ? (
                <PageLoader />
            ) : (
                <div className="container-fluid" style={{ marginBottom: "100px" }}>
                    <div className="card h-100 p-0 radius-12">
                        <div className="card-body p-24">
                            <div className="d-flex justify-content-between align-items-center mb-3">
                                <h6 className="text-lg mb-0">Reservation List</h6>
                                <div className="d-flex align-items-center gap-2">
                                    <button className="btn btn-outline-theme text-sm btn-sm px-12 py-12 radius-8 d-flex align-items-center gap-2" onClick={handleExport}>
                                        <Icon icon="mdi:file-excel" className="me-1" />
                                        Export
                                    </button>
                                    <button
                                        type="button"
                                        onClick={handleCreateDateReservation}
                                        className="btn btn-bg-theme text-sm btn-sm px-12 py-12 radius-8 d-flex align-items-center gap-2"
                                    >
                                        Create
                                    </button>
                                </div>
                            </div>

                            {/* Date Filter */}
                            <div className="row gx-2 gy-2 mb-3">
                                <div className="col-md-3 col-sm-6">
                                    <label className="form-label fw-semibold mb-1">From Date</label>
                                    <input
                                        type="date"
                                        className="form-control"
                                        value={fromDate}
                                        onChange={(e) => setFromDate(e.target.value)}
                                    />
                                </div>
                                <div className="col-md-3 col-sm-6">
                                    <label className="form-label fw-semibold mb-1">To Date</label>
                                    <input
                                        type="date"
                                        className="form-control"
                                        value={toDate}
                                        onChange={(e) => setToDate(e.target.value)}
                                    />
                                </div>
                                <div className="col-md-3 col-sm-12 d-flex align-items-end gap-2">
                                    <button className="btn btn-bg-theme w-100" onClick={applyDateFilter}>
                                        Filter
                                    </button>
                                    <button
                                        className="btn btn-outline-theme w-100"
                                        onClick={() => {
                                            setFromDate("");
                                            setToDate("");
                                            setDateReservation(allReservations);
                                        }}
                                    >
                                        Reset
                                    </button>
                                </div>
                            </div>

                            {/* Table */}
                            <div className="table-responsive scroll-sm">
                                <table className="table bordered-table sm-table mb-0">
                                    <thead>
                                        <tr>
                                            <th className="text-center">Customer Name</th>
                                            <th className="text-center">Phone Number</th>
                                            <th className="text-center">Email</th>
                                            <th className="text-center">Reservation Date</th>
                                            <th className="text-center">Table</th>
                                            <th className="text-center">Party Size</th>
                                            <th className="text-center">Time Slot</th>
                                            <th className="text-center">Status</th>
                                            <th className="text-center">Actions</th>
                                        </tr>
                                    </thead>
                                    <tbody>

                                        {
                                            dateReservation.length === 0 ? (
                                                <tr>
                                                    <td className="text-center" colSpan={9}>
                                                        No data found
                                                    </td>
                                                </tr>
                                            ) : dateReservation.map((reservation) => (
                                                <tr key={reservation?.name}>
                                                    <td className="text-center">{reservation?.customer_name}</td>
                                                    <td className="text-center">
                                                        <Link href={`tel:${reservation?.phonenumber}`} className="text-blue-600 underline">
                                                            {reservation?.phonenumber}
                                                        </Link>
                                                    </td>
                                                    <td className="text-center">
                                                        <Link href={`mailto:${reservation?.email}`} className="text-blue-600 underline">
                                                            {reservation?.email}
                                                        </Link>
                                                    </td>
                                                    <td className="text-center">
                                                        {reservation?.reservation_date ? dayjs(reservation.reservation_date).format("DD-MMM-YYYY") : ""}
                                                    </td>
                                                    <td className="text-center">{reservation?.tablename}</td>
                                                    <td className="text-center">{reservation?.partysize}</td>
                                                    <td className="text-center">{formatTime(reservation?.timeslot)}</td>
                                                    <td className="text-center">
                                                        <span
                                                            className={`px-24 py-4 rounded-pill fw-medium text-sm cursor-pointer ${statusStyles[reservation.status] || "bg-secondary text-white"
                                                                }`}
                                                            onClick={(e) => {
                                                                e.preventDefault();
                                                                setDeleteConfirm({ show: true, id: reservation.name });
                                                                setSelectedStatus(reservation.status);
                                                            }}
                                                        >
                                                            {reservation.status}
                                                        </span>
                                                    </td>
                                                    <td className="text-center">
                                                        <div className="d-flex justify-content-center gap-3">
                                                            <button
                                                                type="button"
                                                                onClick={() => handleEditModel(reservation)}
                                                                className="bg-success-100 text-success-600 w-40-px h-40-px d-flex justify-content-center align-items-center rounded-circle"
                                                            >
                                                                <Icon icon="lucide:edit" className="menu-icon" />
                                                            </button>
                                                        </div>
                                                    </td>
                                                </tr>
                                            ))}
                                    </tbody>
                                </table>
                            </div>
                        </div>
                    </div>
                </div>
            )}

            {/* Status Modal */}
            {deleteConfirm.show && (
                <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-body">
                                <div className="d-flex justify-content-between mb-3">
                                    <h6 className="text-xl mb-0">Update Reservation Status</h6>
                                    <button
                                        type="button"
                                        className="btn-close"
                                        onClick={() => setDeleteConfirm({ show: false, id: null })}
                                    ></button>
                                </div>

                                <div className="mb-3">
                                    <label className="form-label fw-semibold">Select Status</label>
                                    <select
                                        className="form-select"
                                        value={selectedStatus}
                                        onChange={(e) => setSelectedStatus(e.target.value)}
                                    >
                                        <option value="">-- Choose Status --</option>
                                        <option value="Available">Available</option>
                                        <option value="Reserved">Reserved</option>
                                        <option value="Booked">Booked</option>
                                        <option value="Cancelled">Cancelled</option>
                                        <option value="Order Completed">Order Completed</option>
                                    </select>
                                </div>

                                <div className="d-flex justify-content-end gap-2">
                                    <button className="btn btn-outline-theme" onClick={() => setDeleteConfirm({ show: false, id: null })}>
                                        Cancel
                                    </button>
                                    <button className="btn btn-bg-theme" onClick={handleStatusUpdate}>
                                        Submit
                                    </button>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            )}
        </>
    );
};

export default ReservationListComponent;
