import { useState } 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 { 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';

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();
    if (status === "loading") {
        return <div className="flex justify-center items-center h-screen">Loading...</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 mx-auto p-4">
                    <h1 className="text-2xl md:text-3xl font-bold text-center my-4">Моите смени</h1>
                    <div className="space-y-4">
                        {assignments && 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 sm:grid sm:grid-cols-3 sm:gap-4 sm:px-6">
                                            <dt className="text-sm font-medium text-gray-500">Час</dt>
                                            <dd className="mt-1 text 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 sm:grid sm:grid-cols-3 sm:gap-4 sm:px-6">
                                            <dt className="text-sm font-medium text-gray-500">Смяна</dt>
                                            <dd className="mt-1 text 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-1 py-0.5 rounded-full text-sm font-medium ">
                                                            {a.publisher.firstName} {a.publisher.lastName}{a.isWithTransport && <LocalShippingIcon style={{ paddingLeft: '4px' }} />}
                                                        </span>
                                                    )
                                                }
                                                )}
                                            </dd>
                                        </div>
                                        <div className="bg-white px-4 py-5 sm:grid sm:grid-cols-3 sm:gap-4 sm:px-6">
                                            <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"
                                                    onClick={() => AddToGoogleCalendar(assignment.id)}
                                                >
                                                    Добави в календар
                                                </button>
                                                <button
                                                    className="inline-flex items-center px-3 py-2 border border-transparent text-sm leading-4 font-medium rounded-md shadow-sm text-white bg-blue-600 hover:bg-blue-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-blue-500"
                                                    onClick={() => {
                                                        setАssignment(assignment);
                                                        setIsModalOpen(true)
                                                    }}
                                                >
                                                    Заместник
                                                </button>
                                                {/* <button
                                                    className="inline-flex items-center px-3 py-2 border border-transparent text-sm leading-4 font-medium rounded-md shadow-sm text-white bg-blue-600 hover:bg-blue-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-blue-500"
                                                    onClick={() => searchReplacement(assignment.id)}
                                                >
                                                    Търси заместник
                                                </button> */}
                                            </dd>
                                        </div>
                                    </dl>
                                </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 getSession(context);

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

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

    const prisma = common.getPrismaClient();
    const publisher = await prisma.publisher.findMany({
        where: {
            id: session.user.id,
            assignments: {
                some: {
                    shift: {
                        startTime: {
                            gte: new Date(),
                        },
                    },
                },
            },
        },
        include: {
            assignments: {
                include: {
                    shift: {
                        include: {
                            assignments: {
                                include: {
                                    publisher: {
                                        select: {
                                            id: true,
                                            firstName: true,
                                            lastName: true,
                                        }
                                    }
                                }
                            }
                        },
                    },
                },
            },
        },
    });

    const assignments = publisher[0]?.assignments || [];

    const transformedAssignments = assignments?.map(assignment => {
        if (assignment.shift && assignment.shift.startTime) {
            return {
                ...assignment,
                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 }
    }
}

