import { CartEvent, UserRole } from '@prisma/client';
import { useRouter } from "next/router";
import { useState } from "react";
import Layout from "../../../components/layout";

import common from 'src/helpers/common';
import ProtectedRoute from '../../../components/protectedRoute';


import CartEventForm from '../../../components/cartevent/CartEventForm';
// import IProps from '../../../components/cartevent/CartEventForm'

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

// export default CartEventForm;
export interface ICartEventPageProps {
  items: [CartEvent];
  locations: [Location];
  inline: false;
}

export default function CartEventPage({ items, locations }: ICartEventPageProps) {

  const router = useRouter();
  const [addnew, setAddNew] = useState(false);

  return (
    <Layout>
      <ProtectedRoute allowedRoles={[UserRole.POWERUSER, UserRole.ADMIN]}>
        <div className="flex flex-col">
          <h1>All cart events</h1>
          <table className="min-w-full">
            <thead className="border-b">
              <tr>
                <th scope="col" className="text-sm font-medium text-gray-900 px-6 py-4 text-left">
                  #
                </th>
                <th scope="col" className="text-sm font-medium text-gray-900 px-6 py-4 text-left">
                  Day of Week
                </th>
                <th scope="col" className="text-sm font-medium text-gray-900 px-6 py-4 text-left">
                  Time
                </th>
                <th scope="col" className="text-sm font-medium text-gray-900 px-6 py-4 text-left">
                  Shift Duration
                </th>
                <th scope="col" className="text-sm font-medium text-gray-900 px-6 py-4 text-left">
                  Active
                </th>
              </tr>
            </thead>
            <tbody>
              {items.map((item: CartEvent, i) => (
                <tr key={i} className="border-b">
                  <td className="px-6 py-4 whitespace-nowrap">
                    {item.id}
                  </td>
                  <td className="px-6 py-4 whitespace-nowrap">
                    <strong>{common.dayOfWeekNames[common.getDayOfWeekIndex(item.dayofweek)]} </strong>
                    на {locations.find(l => l.id == item.locationId).name}
                  </td>
                  <td className="px-6 py-4 whitespace-nowrap">
                    {new Date(item.startTime).toLocaleTimeString('en-US', { hour: '2-digit', minute: '2-digit' })
                      + " до " + new Date(item.endTime).toLocaleTimeString('en-US', { hour: '2-digit', minute: '2-digit' })}
                  </td>
                  <td className="px-6 py-4 whitespace-nowrap">
                    {item.shiftDuration}
                  </td>
                  <td className="px-6 py-4 whitespace-nowrap">
                    {item.isactive ? "Yes" : "No"}
                  </td>
                  <td>
                    <button className="button bg-blue-500 hover:bg-blue-700"
                      onClick={() => router.push(`/cart/cartevents/edit/${item.id}`)}
                    >
                      Edit
                    </button>
                  </td>
                </tr>
              ))}
            </tbody>
          </table>
          <button className="button bg-blue-500 hover:bg-blue-700"
            onClick={() => setAddNew(!addnew)}
          > {addnew ? "Отмени" : "Добави нов"}</button>
          {addnew && <CartEventForm locations={locations} />}
        </div>
      </ProtectedRoute>
    </Layout>
  )
}


export const getServerSideProps = async (context) => {


  const session = await getServerSession(context.req, context.res, authOptions)
  context.req.session = session;
  const axios = await axiosServer(context);

  const { data: items } = await axios.get("/api/data/cartevents");
  console.log("gettnng locations from: " + "/api/data/locations?select=id,name");
  const locations = await axios
    .get(`/api/data/locations?select=id,name`)
    .then((res) => {
      console.log("locations: " + JSON.stringify(res.data));
      return res.data;
    });

  return {
    props: {
      items,
      locations: locations,
      inline: false,
    },
  };
};