import { useState, useEffect } from 'react';
import Layout from "../../../components/layout";
import ProtectedRoute from '../../../components/protectedRoute';
import { UserRole } from '@prisma/client';
import axiosServer from '../../../src/axiosServer';
import common from '../../../src/helpers/common';
import Modal from 'components/Modal';
import ConfirmationModal from 'components/ConfirmationModal';
import PublisherSearchBox from '../../../components/publisher/PublisherSearchBox'; // Update the path
import SearchReplacement from '../../../components/publisher/SearchReplacement'; // Update the path

import { monthNamesBG, GetTimeFormat, GetDateFormat } from "../../../src/helpers/const"
import { useSession, getSession } from 'next-auth/react';
import axiosInstance from 'src/axiosSecure';
import { toast } from 'react-toastify';
import LocalShippingIcon from '@mui/icons-material/LocalShipping';
import { getServerSession } from 'next-auth';
import { authOptions } from 'pages/api/auth/[...nextauth]';

export default function MySchedulePage({ assignments }) {

    const [isModalOpen, setIsModalOpen] = useState(false);
    const [isConfirmModalOpen, setIsConfirmModalOpen] = useState(false);
    const [useFilterDate, setUseFilterDate] = useState(true);
    const [assignment, setАssignment] = useState(null);
    const [newPublisher, setNewPublisher] = useState(null);

    const { data: session, status } = useSession();

    // temporary alert for the users
    // useEffect(() => {
    //     alert("Мили братя, искаме само да ви напомним да ни изпратите вашите предпочитания за юни до 25-то число като използвате меню 'Възможности'. Ако имате проблем, моля пишете ни на 'specialnosvidetelstvanesofia@gmail.com'");
    // }, []);

    if (status === "loading") {
        return <div className="flex justify-center items-center h-screen">Зареждане...</div>;
    }


    const handleReplaceInAssignment = () => {
        // Add publisher as assignment logic
        setIsModalOpen(false);
        setIsConfirmModalOpen(false);
        console.log("publisher", newPublisher.firstName, " ", newPublisher.lastName, " set to shift ", assignment.shift.id);
        //api.replaceInAssignment()
        axiosInstance.post('/api/?action=replaceInAssignment', {
            oldPublisherId: session.user.id,
            newPublisherId: newPublisher.id,
            shiftId: assignment.shift.id,
        }).then(response => {
            console.log("response", response);
            //toast success and confirm the change
            // refresh the page after toast is closed
            toast.success("Промяната е записана!", {
                onClose: () => {
                    window.location.reload();

                }
            });
        }).catch(error => {
            console.log("error", error);
        });
    };


    return (
        <Layout>
            <ProtectedRoute allowedRoles={[UserRole.ADMIN, UserRole.POWERUSER, UserRole.USER]}>
                <div className="container ">
                    <h1 className="text-xl sm:text-2xl md:text-3xl font-bold text-center my-4">Моите смени</h1>
                    <div className="space-y-4">
                        {assignments && assignments.length > 0 ? (assignments.map((assignment) => (
                            <div key={assignment.dateStr + assignments.indexOf(assignment)} className="bg-white shadow overflow-hidden rounded-lg">
                                <div className="px-4 py-5 sm:px-6">
                                    <h3 className="text-lg leading-6 font-medium text-gray-900">{assignment.dateStr}</h3>
                                </div>
                                <div className="border-t border-gray-200">
                                    <dl>
                                        <div className="bg-gray-50 px-4 py-5 grid grid-cols-1 sm:grid-cols-3 gap-4 xs:gap-1 px-6 xs:py-1">
                                            <dt className="text-sm font-medium text-gray-500">Място</dt>
                                            <dd className="mt-1 text-sm text-gray-900 sm:mt-0 sm:col-span-2">
                                                {assignment.shift.cartEvent.location.name}
                                            </dd>
                                        </div>
                                        <div className="bg-gray-50 px-4 py-5 grid grid-cols-1 sm:grid-cols-3 gap-4 xs:gap-1 px-6 xs:py-1">
                                            <dt className="text-sm font-medium text-gray-500">Час</dt>
                                            <dd className="mt-1 text-sm text-gray-900 sm:mt-0 sm:col-span-2">
                                                {GetTimeFormat(assignment.shift.startTime)} - {GetTimeFormat(assignment.shift.endTime)}
                                            </dd>
                                        </div>
                                        <div className="bg-gray-50 px-4 py-5 grid grid-cols-1 sm:grid-cols-3 gap-4 xs:gap-1  px-6 xs:py-1">
                                            <dt className="text-sm font-medium text-gray-500">Смяна</dt>
                                            <dd className="mt-1 text-sm text-gray-900 sm:mt-0 sm:col-span-2">
                                                {assignment.shift.assignments.map((a, index) => {
                                                    return (
                                                        <span key={index} className="inline-flex items-center mr-1 px-2 py-0.5 my-0.5 border border-gray-300 rounded-full text-sm font-medium bg-gray-100">
                                                            {a.publisher.firstName} {a.publisher.lastName}
                                                            {a.isWithTransport && <LocalShippingIcon style={{ marginLeft: '4px' }} />}
                                                        </span>
                                                    )
                                                }
                                                )}
                                            </dd>
                                        </div>
                                        {!assignment.isOld &&

                                            <div className="bg-gray-50 px-4 py-5 grid grid-cols-1 sm:grid-cols-3 gap-4 xs:gap-1 px-6 xs:py-1">
                                                <dt className="text-sm font-medium text-gray-500">Действия</dt>
                                                <dd className="mt-1 text-sm text-gray-900 sm:mt-0 sm:col-span-2">
                                                    <button
                                                        className="mr-2 mb-2 inline-flex items-center px-3 py-2 border border-transparent text-sm leading-4 font-medium rounded-md shadow-sm text-white bg-green-600 hover:bg-green-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-green-500 disabled"
                                                        disabled={true}
                                                        // disabled={assignment.isInGoogleCalendar}
                                                        onClick={() => SaveEventsInGoogleCalendar(assignment)}
                                                    >
                                                        Добави в календар
                                                    </button>
                                                    <button
                                                        className="mr-2 mb-2 inline-flex items-center px-3 py-2 border border-transparent text-sm leading-4 font-medium rounded-md shadow-sm text-white bg-green-600 hover:bg-green-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-blue-500"
                                                        onClick={() => {
                                                            setАssignment(assignment);
                                                            setIsModalOpen(true)
                                                        }}
                                                    >
                                                        Избери Заместник
                                                    </button>

                                                    <SearchReplacement shiftId={assignment.shift.id} assignmentId={assignment.id} />
                                                </dd>
                                            </div>
                                        }
                                    </dl>
                                </div>
                            </div>
                        ))) :
                            <div className="bg-white shadow overflow-hidden rounded-lg">
                                <div className="px-4 py-5 sm:px-6">
                                    <h3 className="text-lg leading-6 font-medium text-gray-900">За сега нямате бъдещи назначени смени. Можете да проверите дали вашите възножности са актуални.</h3>
                                </div>
                            </div>
                        }
                    </div>
                </div>
                <Modal isOpen={isModalOpen}
                    onClose={() => setIsModalOpen(false)}
                    forDate={new Date(assignment?.shift.startTime)}
                    useFilterDate={useFilterDate}
                    onUseFilterDateChange={(value) => setUseFilterDate(value)}>

                    <PublisherSearchBox
                        selectedId={null}
                        isFocused={isModalOpen}
                        filterDate={useFilterDate && assignment ? new Date(assignment.shift.startTime) : null}
                        onChange={(publisher) => {
                            setIsConfirmModalOpen(true);
                            setNewPublisher(publisher);
                        }}
                        showAllAuto={true}
                        showSearch={true}
                        showList={false}
                    />
                </Modal>

                <ConfirmationModal
                    isOpen={isConfirmModalOpen}
                    onClose={() => { setIsConfirmModalOpen(false); setNewPublisher(null); }}
                    onConfirm={handleReplaceInAssignment}
                    message="Това действие ще те замести в назначената ти смяна. Потвърждаваш ли, че заместника знае за тази промяна."
                />
            </ProtectedRoute>
        </Layout>
    );
}

//get future assignments for the current user (session.user.id)

export const getServerSideProps = async (context) => {
    const session = await getServerSession(context.req, context.res, authOptions)

    context.res.setHeader("Cache-Control", "s-maxage=1, stale-while-revalidate");

    if (!session) {
        return {
            redirect: {
                destination: '/auth/signin', // Adjust the login path as needed
                permanent: false,
            },
        };
    }

    const prisma = common.getPrismaClient();
    let today = new Date();
    today.setHours(0, 0, 0, 0);
    // const monthInfo = common.getMonthInfo(today);
    // //minus 1 day from the firstMonday to get the last Sunday
    // const lastSunday = new Date(monthInfo.firstMonday);
    // lastSunday.setDate(lastSunday.getDate() - 1);
    const publisher = await prisma.publisher.findUnique({
        where: {
            id: session.user.id,
            assignments: {
                some: {
                    shift: {
                        startTime: {
                            gte: today,
                        },
                    },
                },
            },
        },
        include: {
            assignments: {
                include: {
                    shift: {
                        include: {
                            assignments: {
                                include: {
                                    publisher: {
                                        select: {
                                            id: true,
                                            firstName: true,
                                            lastName: true,
                                        }
                                    }
                                }
                            },
                            cartEvent: {
                                select: {
                                    id: true,
                                    dayofweek: true,
                                    location: {
                                        select: {
                                            name: true,
                                        }
                                    }
                                }
                            }
                        },
                    },
                },
            },
        },
    });

    const assignments = publisher?.assignments.filter(a => a.shift.startTime >= today && a.shift.isPublished) || [];


    const transformedAssignments = assignments?.sort((a, b) => a.shift.startTime - b.shift.startTime)
        .map(assignment => {
            if (assignment.shift && assignment.shift.startTime) {
                return {
                    ...assignment,
                    isOld: assignment.shift.startTime < new Date(),
                    dateStr: assignment.shift.startTime.toLocaleDateString("bg-BG", { day: "numeric", month: "long" }),
                    shift: {
                        ...assignment.shift,
                        startTime: assignment.shift.startTime.toISOString(),
                        endTime: assignment.shift.endTime.toISOString(),
                    },
                };
            }
            return assignment;
        });



    return {
        props: { assignments: transformedAssignments }
    }
}

