import axiosInstance from '../../src/axiosSecure';
import { useEffect, useState } from "react";
import toast from "react-hot-toast";
import { useRouter } from "next/router";
import Link from "next/link";
import { DayOfWeek } from "../DayOfWeek";
const common = require('src/helpers/common');

import AvailabilityForm from "../availability/AvailabilityForm";

import { TrashIcon, PencilSquareIcon } from "@heroicons/react/24/outline";
import { Availability, AvailabilityType } from "@prisma/client";



export default function AvailabilityList({ publisher, showNew }) {
    const [showAv, setShowAv] = useState(showNew || false);
    const [selectedItem, setSelectedItem] = useState(null);
    const [items, setItems] = useState(publisher.availabilities); // Convert items prop to state
    const [blockedAvailabilityDate, setBlockedAvailabilityDate] = useState(null);

    useEffect(() => {
        console.log('items set to:', items?.map(item => item.id));
    }, [items])

    useEffect(() => {
        axiosInstance.get(`/api/?action=settings&key=AvailabilityBlockDate`)
            .then(({ data }) => {
                setBlockedAvailabilityDate(new Date(data.value));
            })
            .catch(error => {
                console.error("Error getting blocked date:", error);
            });
    }, []);

    const toggleAv = () => setShowAv(!showAv);
    const editAvailability = (item) => {
        setSelectedItem(item);
        setShowAv(true)
    };

    const deleteAvailability = async (id) => {
        try {
            await axiosInstance.delete("/api/data/availabilities/" + id);
            // Handle the successful deletion, maybe refresh the list or show a success message
            const updatedItems = items.filter(item => item.id !== id);
            setItems(updatedItems);
        } catch (error) {
            // Handle the error, maybe show an error message
            console.error("Error deleting availability:", error);
        }
    };

    const renderTable = () => (
        <table className="min-w-full">
            <thead className="border-b">
                <tr>
                    <th scope="col" className="text-sm font-medium text-gray-900 px-6 py-4 text-left">
                        Ден от седмицата (дата)
                    </th>
                    <th scope="col" className="text-sm font-medium text-gray-900 px-6 py-4 text-left">
                        От-до
                    </th>
                    <th scope="col" className="text-sm font-medium text-gray-900 px-6 py-4 text-left">
                        Действия
                    </th>
                </tr>
            </thead>
            <tbody>
                {items?.sort((a, b) => new Date(a.startTime) - new Date(b.startTime)).map(item => (
                    <tr key={item.id} availability={item} disabled={!item.isActive} className={`${item.isFromPreviousMonth ? 'bg-yellow-200' : ''} ${!item.isActive ? 'opacity-50' : ''}`}>
                        <td className="px-6 py-4 whitespace-nowrap">
                            {item.type == AvailabilityType.OneTime ? `${common.getDateFormated(new Date(item.startTime))}` :
                                item.type == AvailabilityType.Weekly ? `Всеки(Всяка) ${common.getDayOfWeekName(new Date(item.startTime))}` : "месечно"

                            }
                            {/* {common.getDateFormated(new Date(item.startTime))} */}
                        </td>
                        <td className="px-6 py-4 whitespace-nowrap">
                            {common.getTimeRange(new Date(item.startTime), new Date(item.endTime))}
                        </td>
                        <td className="px-6 py-4 whitespace-nowrap text-sm">
                            {/* <button className="bg-blue-200 hover:bg-blue-300 text-blue-600 py-1 px-2 rounded inline-flex items-center" onClick={() => editAvailability(item)}>
                                <PencilSquareIcon className="h-6 w-6" />
                            </button> */}
                            {(blockedAvailabilityDate && new Date(item.startTime) < blockedAvailabilityDate) ? (
                                <button className="disabled bg-gray-200 hover:bg-gray-300 text-gray-600 py-1 px-2 rounded inline-flex items-center">
                                    <TrashIcon className="h-6 w-6" />
                                </button>
                            ) : (
                                <button className="bg-red-200 hover:bg-red-300 text-red-600 py-1 px-2 rounded ml-2 inline-flex items-center" onClick={() => deleteAvailability(item.id)}>
                                    <TrashIcon className="h-6 w-6" />
                                </button>
                            )}

                        </td>
                    </tr>
                ))}
            </tbody>
        </table>
    );


    return (
        <>
            {items?.length === 0 ? (
                <h1>No Availabilities</h1>
            ) : renderTable()}

            {<div className="flex justify-center mt-2">
                <button className="btn bg-blue-500 hover:bg-blue-600 text-white font-semibold py-2 px-4 rounded transition duration-300"
                    onClick={() => { setSelectedItem(null); setShowAv(true) }}>Добави нова възможност</button>
            </div>
            }
            <div className="h-4 p-10">
                {showAv && (
                    <AvailabilityForm
                        publisherId={publisher.id}
                        inline={true}
                        existingItems={selectedItem ? [selectedItem] : []}
                        date={selectedItem ? new Date(selectedItem.startTime) : new Date()}
                        datePicker={true}
                        onDone={(item) => {
                            toggleAv();
                            setSelectedItem(null);
                            //get the updated list of availabilities from the server
                            axiosInstance.get(common.getBaseUrl("/api/data/availabilities"))
                                .then(({ data: items }) => {
                                    setItems(items);
                                })
                                .catch(error => {
                                    console.error("Error getting availabilities:", error);
                                });
                        }}
                    />
                )}
            </div>
        </>
    );


}

// export const getServerSideProps = async () => {
//     const { data: items } = await axiosInstance.get(
//         common.getBaseUrl("/api/data/availabilities")
//     );

//     return {
//         props: {
//             items,
//         },
//     };
// };