import { useSession } from "next-auth/react"
import { useRouter } from 'next/router';
import React, { useState, useEffect } from 'react';
import Layout from "../components/layout"

import AvCalendar from '../components/calendar/avcalendar';
import { getSession } from "next-auth/react";
import common from '../src/helpers/common';
import { Availability, UserRole } from "@prisma/client";
import ProtectedRoute, { serverSideAuth } from "../components/protectedRoute";
import axiosInstance from '../src/axiosSecure';
// const dataHelper = require('../../src/helpers/data');
import dataHelper from '../src/helpers/data';

import { authOptions } from './api/auth/[...nextauth]'
import { getServerSession } from "next-auth/next"

import PublisherSearchBox from '../components/publisher/PublisherSearchBox';
import PublisherInlineForm from '../components/publisher/PublisherInlineForm';
import CartEventForm from "components/cartevent/CartEventForm";


interface IProps {
    initialItems: Availability[];
    initialUserId: string;
    cartEvents: any;
    lastPublishedDate: Date;
}
export default function DashboardPage({ initialItems, initialUserId, cartEvents, lastPublishedDate }: IProps) {

    const router = useRouter();
    const { newLogin } = router.query;
    const { data: session } = useSession();
    const [userName, setUserName] = useState('');
    const [userId, setUserId] = useState(initialUserId);
    const [events, setEvents] = useState(initialItems?.map(item => ({
        ...item,
        title: item.name,
        date: new Date(item.startTime),
        startTime: new Date(item.startTime),
        endTime: new Date(item.endTime),
        publisherId: item.publisherId,
    })));

    useEffect(() => {
        if (session && userName === '' && session.user.name) {
            setUserName(session.user.name);
            setUserId(session.user.id);
            //handleUserSelection({ id: session.user.id, firstName: session.user.name, lastName: '' });
        }
    }, [session]);


    //const [notificationsVisible, setNotificationsVisible] = useState(false);

    useEffect(() => {
        //if (newLogin === 'true') 
        {
            // alert("Мили братя, искаме само да ви напомним да ни изпратите вашите предпочитания за юни до 25-то число като използвате меню 'Възможности'. Ако имате проблем, моля пишете ни на 'specialnosvidetelstvanesofia@gmail.com'");
            const currentPath = router.pathname;
            router.replace(currentPath, undefined, { shallow: true });  // Removes the query without affecting the history
        }
    }, []);// show the message every time we load the page

    const handleUserSelection = async (publisher) => {
        if (!publisher || publisher.id === undefined) return;
        console.log("selecting publisher", publisher.id);
        setUserName(publisher.firstName + " " + publisher.lastName);
        setUserId(publisher.id);

        try {
            let events = await axiosInstance.get(`/api/?action=getCalendarEvents&publisherId=${publisher.id}`);
            setEvents(events.data);
        } catch (error) {
            console.error("Error fetching publisher info:", error);
            // Handle the error appropriately
        }
    };

    // EXAMPLE USAGE OF ProtectedRoute
    ProtectedRoute.IsInRole(UserRole.ADMIN).then(isAdmin => {
        if (isAdmin) {
            console.log("User is an admin.");
        } else {
            console.log("User is not an admin.");
        }
    });

    return (
        <Layout>
            <ProtectedRoute allowedRoles={[UserRole.ADMIN, UserRole.POWERUSER, UserRole.USER, UserRole.EXTERNAL]} deniedMessage="">
                <h1 className="pt-2 pb-1 text-xl font-bold text-center">Графика на {userName}</h1>
                <ProtectedRoute allowedRoles={[UserRole.ADMIN]} deniedMessage="">
                    <PublisherSearchBox selectedId={userId} infoText="" onChange={handleUserSelection} />
                </ProtectedRoute>
                <div className="flex flex-row md:flex-row mt-4 xs:mt-1 space-y-4 md:space-y-0 md:space-x-4 h-[calc(100vh-10rem)]">
                    <div className="flex-1">
                        <div className="text-center font-bold pb-3 xs:pb-1">
                            <PublisherInlineForm publisherId={userId} />
                        </div>
                        <AvCalendar publisherId={userId} events={events} selectedDate={new Date()} cartEvents={cartEvents} lastPublishedDate={lastPublishedDate} />
                    </div>
                </div>
            </ProtectedRoute>
        </Layout>
    );
}


// async function getAvailabilities(userId) {
//     const prismaClient = common.getPrismaClient();
//     const items = await prismaClient.availability.findMany({
//         where: {
//             publisherId: userId,
//         },
//         select: {
//             id: true,
//             name: true,
//             isActive: true,
//             isFromPreviousAssignment: true,
//             isFromPreviousMonth: true,
//             dayofweek: true,
//             dayOfMonth: true,
//             startTime: true,
//             endTime: true,
//             repeatWeekly: true,
//             endDate: true,
//             publisher: {
//                 select: {
//                     firstName: true,
//                     lastName: true,
//                     id: true,
//                 },
//             },
//         },
//     });
//     // Convert Date objects to ISO strings
//     const serializableItems = items.map(item => ({
//         ...item,
//         startTime: item.startTime.toISOString(),
//         endTime: item.endTime.toISOString(),
//         name: common.getTimeFormatted(item.startTime) + "-" + common.getTimeFormatted(item.endTime),
//         //endDate can be null
//         endDate: item.endDate ? item.endDate.toISOString() : null,
//         type: 'availability',
//         // Convert other Date fields similarly if they exist
//     }));

//     /*model Assignment {
//   id              Int       @id @default(autoincrement())
//   shift           Shift     @relation(fields: [shiftId], references: [id], onDelete: Cascade)
//   shiftId         Int
//   publisher       Publisher @relation(fields: [publisherId], references: [id], onDelete: Cascade)
//   publisherId     String
//   isActive        Boolean   @default(true)
//   isConfirmed     Boolean   @default(false)
//   isWithTransport Boolean   @default(false)
//   Report          Report[]
// }*/
//     //get assignments for this user
//     const assignments = await prismaClient.assignment.findMany({
//         where: {
//             publisherId: userId,
//         },
//         select: {
//             id: true,
//             isBySystem: true,
//             isConfirmed: true,
//             isWithTransport: true,
//             shift: {
//                 select: {
//                     id: true,
//                     name: true,
//                     startTime: true,
//                     endTime: true,
//                     //select all assigned publishers names as name - comma separated
//                     assignments: {
//                         select: {
//                             publisher: {
//                                 select: {
//                                     firstName: true,
//                                     lastName: true,
//                                 }
//                             }
//                         }
//                     }
//                 }
//             }
//         }
//     });

//     const serializableAssignments = assignments.map(item => ({
//         ...item,
//         startTime: item.shift.startTime.toISOString(),
//         endTime: item.shift.endTime.toISOString(),
//         // name: item.shift.publishers.map(p => p.firstName + " " + p.lastName).join(", "),
//         //name: item.shift.assignments.map(a => a.publisher.firstName[0] + " " + a.publisher.lastName).join(", "),
//         name: common.getTimeFormatted(new Date(item.shift.startTime)) + "-" + common.getTimeFormatted(new Date(item.shift.endTime)),
//         type: 'assignment',
//         //delete shift object
//         shift: null,
//         publisher: { id: userId }
//     }));

//     serializableItems.push(...serializableAssignments);

//     return serializableItems;

// }

export const getServerSideProps = async (context) => {
    const auth = await serverSideAuth({
        req: context.req,
        allowedRoles: [/* ...allowed roles... */]
    });
    // const session = await getSession(context);
    const sessionServer = await getServerSession(context.req, context.res, authOptions)

    if (!sessionServer) {
        return {
            redirect: {
                destination: '/auth/signin',
                permanent: false,
            },
        };
    }

    const role = sessionServer?.user.role;
    console.log("server role: " + role);
    const userId = sessionServer?.user.id;
    var isAdmin = sessionServer?.user.role == UserRole.ADMIN;//role.localeCompare(UserRole.ADMIN) === 0;

    var items = await dataHelper.getCalendarEvents(userId, true, true, isAdmin);
    // common.convertDatesToISOStrings(items);
    //serializable dates
    items = items.map(item => {
        const updatedItem = {
            ...item,
            startTime: item.startTime.toISOString(),
            endTime: item.endTime.toISOString(),
            date: item.date.toISOString(),
            name: common.getTimeFormatted(item.startTime) + "-" + common.getTimeFormatted(item.endTime)
        };

        if (updatedItem.shift) {
            updatedItem.shift = {
                ...updatedItem.shift,
                startTime: updatedItem.shift.startTime.toISOString(),
                endTime: updatedItem.shift.endTime.toISOString()
            };
            updatedItem.isPublished = updatedItem.shift.isPublished;
        }

        return updatedItem;
    });

    // log first availability startTime to verify timezone and UTC conversion

    const prisma = common.getPrismaClient();
    let cartEvents = await prisma.cartEvent.findMany({
        where: {
            isActive: true,
        },
        select: {
            id: true,
            startTime: true,
            endTime: true,
            dayofweek: true,
            shiftDuration: true,
        }
    });
    cartEvents = common.convertDatesToISOStrings(cartEvents);
    let lastPublishedDate = (await prisma.shift.findFirst({
        where: {
            isPublished: true,
        },
        select: {
            endTime: true,
        },
        orderBy: {
            endTime: 'desc'
        }
    }))?.endTime || new Date();

    let blockedDate = await prisma.settings.findUnique({
        where: {
            key: "AvailabilityBlockDate"
        }
    });

    if (blockedDate) {
        blockedDate.value = new Date(blockedDate.value);
        lastPublishedDate = lastPublishedDate > blockedDate.value ? lastPublishedDate : blockedDate.value;
    }

    return {
        props: {
            initialItems: items,
            userId: sessionServer?.user.id,
            cartEvents: cartEvents,
            lastPublishedDate: lastPublishedDate.toISOString(),
            // messages: (await import(`../content/i18n/${context.locale}.json`)).default
        },
    };
}
