import React, { useState, useEffect } from 'react';
import Layout from "../../../components/layout";
import { GetServerSideProps } from 'next';
import { Location, UserRole } from "@prisma/client";
import axiosServer from '../../../src/axiosServer';
const common = require('../../../src/helpers/common');
// import * as common from '../../../src/helpers/common';
import SurveyForm from '../../../components/survey/SurveyForm';
import _ from 'lodash';

const SurveyPage = ({ serverSurveys }) => {
    const [selectedSurvey, setSelectedSurvey] = useState(null);

    return (
        <Layout>
            <div className="view-location-page max-w-4xl mx-auto my-8">
                <h1>Survey Page</h1>
            </div>

            <div className="flex flex-row justify-between">
                <div className="w-1/2">
                    <h2>Surveys</h2>
                    <ul>
                        {serverSurveys.map((survey) => (
                            <li key={survey.id}>
                                {survey.id}: {survey.context}: <br />
                                {Object.entries(_.groupBy(survey.messages, 'answer')).map(([key, items]) => (
                                    <div key={key}>
                                        {key}: {items.length}
                                    </div>
                                ))}
                                <button className='btn' onClick={() => setSelectedSurvey(survey)}>Edit</button>
                            </li>
                        ))}
                    </ul>
                    <button className='btn' onClick={() => setSelectedSurvey(null)}>New Survey</button>
                </div>
                <div className="w-1/2">
                    <h2>Selected Survey</h2>
                    {selectedSurvey && (
                        <div>
                            <h3>{selectedSurvey.title}</h3>
                            <p>{selectedSurvey.description}</p>
                        </div>
                    )}
                </div>
            </div>
            <SurveyForm existingItem={selectedSurvey} />
        </Layout>
    );
};

export default SurveyPage;

export const getServerSideProps: GetServerSideProps = async (context) => {
    const prisma = common.getPrismaClient();
    let serverSurveys = await prisma.survey.findMany({
        where: {
        },
        include: {
            messages: true,
        },
    });
    serverSurveys = common.convertDatesToISOStrings(serverSurveys);

    context.res.setHeader("Cache-Control", "s-maxage=1, stale-while-revalidate");
    return {
        props: {
            serverSurveys: serverSurveys
        },
    };
};

