import { useSession } from "next-auth/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 React, { useState, useEffect } from 'react';
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';


interface IProps {
    initialItems: Availability[];
    initialUserId: string;
}
export default function IndexPage({ initialItems, initialUserId }: IProps) {
    const { data: session } = useSession();
    const [userName, setUserName] = useState(session?.user?.name);
    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) {
            setUserName(session.user.name);
            setUserId(session.user.id);
            //handleUserSelection({ id: session.user.id, firstName: session.user.name, lastName: '' });
        }
    }, [session]);

    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()} />
                    </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 (!session) { return { props: {} } }
    const role = session?.user.role;
    console.log("server role: " + role);
    const userId = session?.user.id;

    var items = await dataHelper.getCalendarEvents(session.user.id);
    // common.convertDatesToISOStrings(items);
    //serializable dates
    items = items.map(item => {
        const updatedItem = {
            ...item,
            startTime: item.startTime.toISOString(),
            endTime: item.endTime.toISOString(),
            date: item.date.toISOString()
        };

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

        return updatedItem;
    });

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