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 ShiftsList from '../../../components/publisher/ShiftsList';

import { monthNamesBG, GetTimeFormat, GetDateFormat } from "../../../src/helpers/const"
import { useSession, getSession } from 'next-auth/react';

export default function MySchedulePage({ assignments }) {

    const { data: session, status } = useSession();
    if (status === "loading") {
        return <div className="flex justify-center items-center h-screen">Loading...</div>;
    }

    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} 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-sm text-gray-900 sm:mt-0 sm:col-span-2">
                                                {GetTimeFormat(assignment.shift.startTime)} - {GetTimeFormat(assignment.shift.endTime)}
                                            </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={() => searchReplacement(assignment.id)}
                                                >
                                                    Търси заместник
                                                </button>
                                            </dd>
                                        </div>
                                    </dl>
                                </div>
                            </div>
                        ))}
                    </div>
                </div>

            </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: 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 }
    }
}

