import axiosInstance from '../../src/axiosSecure';
import { useEffect, useState } from "react";
import { toast } from 'react-toastify';
import { useRouter } from "next/router";
import Link from "next/link";
import DayOfWeek from "../DayOfWeek";
import { ReportType } from "@prisma/client";
const common = require('src/helpers/common');

import { useSession } from "next-auth/react"

import dynamic from 'next/dynamic';
const ReactQuill = dynamic(() => import('react-quill'), {
    ssr: false,
    loading: () => <p>Loading...</p>,
});
import 'react-quill/dist/quill.snow.css'; // import styles

// ------------------ FeedbackForm ------------------
// This component is used to create and edit 
//  model:
// model Report {
//     id           Int        @id @default(autoincrement())
//     date         DateTime
//     publisher    Publisher  @relation(fields: [publisherId], references: [id], onDelete: Cascade)
//     publisherId  String
//     assignment   Assignment @relation(fields: [assignmentId], references: [id], onDelete: Cascade)
//     assignmentId Int

//     placementCount       Int?
//     videoCount           Int?
//     returnVisitInfoCount Int?
//     conversationCount    Int?

//     experienceInfo String?
//   }

export default function FeedbackForm({ publisherId, onDone }) {
    const { data: session, status } = useSession()
    const [pubId, setPublisher] = useState(publisherId);

    const router = useRouter();

    //get the user from session if publisherId is null
    useEffect(() => {
        if (!publisherId) {
            if (session) {
                setPublisher(session.user.id);
            }
        }
    }, [publisherId, session]);

    const [item, setItem] = useState({
        experienceInfo: "",
        assignmentId: 0,
        publisherId: publisherId,
        date: new Date(),
        placementCount: 1,
        videoCount: 0,
        returnVisitInfoCount: 0,
        conversationCount: 0
    });

    const [locations, setLocations] = useState([]);


    const handleChange = (content, delta, source, editor) => {
        item.experienceInfo = content;
        setItem(item);
        console.log(editor.getHTML()); // rich text
    };

    const handleSubmit = async (e) => {
        e.preventDefault();
        item.publisher = { connect: { id: pubId } };
        //ToDo: create dedicated feedback type instead of using placementCount for subtype
        item.type = item.placementCount === 1 ? ReportType.Feedback_Problem : (item.placementCount === 2 ? ReportType.Feedback_Suggestion : ReportType.Feedback);
        delete item.assignmentId;

        try {
            const response = await axiosInstance.post('/api/data/reports', item);
            console.log(response);
            toast.success("Благодаря за отзива!");
            setTimeout(() => {
                if (onDone) {
                    onDone();
                } else {
                    router.push(`/dash`);
                }
            }, 3000); // Delay for 3 seconds
        } catch (error) {
            console.log(error);
            toast.error("Error saving report");
        }
    }

    const modules = {
        toolbar: {
            container: [
                ['bold', 'italic', 'underline'], // Basic text formats
                [{ 'list': 'ordered' }, { 'list': 'bullet' }], // Lists
                ['link', 'image'] // Media
            ],
        }
    };



    return (
        <div className="w-full max-w-md mx-auto">
            <form className="bg-white dark:bg-gray-800 shadow rounded-lg px-8 pt-6 pb-8 mb-4" onSubmit={handleSubmit} >

                <h1 className="text-2xl font-bold mb-4">Намерих технически проблем:</h1>
                <div className="mb-4">

                    <label className='block text-gray-700 dark:text-gray-300 text-sm font-bold mb-2' htmlFor="location">Тип</label>

                    <select
                        name="placementCount"
                        id="placementCount"
                        value={item.placementCount}
                        onChange={(e) => {
                            setItem(prevItem => ({
                                ...prevItem,
                                placementCount: parseInt(e.target.value)
                            }));
                        }}
                        className="block appearance-none w-full bg-white dark:bg-gray-700 border border-gray-300 dark:border-gray-600 rounded py-2 px-3 text-gray-700 dark:text-gray-300 leading-tight focus:outline-none focus:bg-white focus:border-blue-500"
                    >
                        <option key={1} value={1}>Проблем/Грешка</option>
                        <option key={2} value={2}>Предложение</option>
                        <option key={3} value={3}>Друго</option>
                    </select>

                </div>

                <div className="mb-8"> {/* Increased bottom margin */}

                    <ReactQuill
                        theme="snow"
                        value={item.experienceInfo}
                        onChange={handleChange}
                        modules={modules}
                        className="w-full h-60 pb-6 bg-white dark:bg-gray-700"
                    />
                </div>

                <div className="flex flex-col md:flex-row items-center justify-between mt-"> {/* Adjusted layout and added top margin */}
                    <button className="bg-blue-500 hover:bg-blue-700 text-white font-bold py-2 px-4 rounded focus:outline-none focus:shadow-outline" type="submit">
                        Изпрати
                    </button>

                </div>
            </form >
        </div >
    );
}


