import RequestedBy from "@/components/ApprovalWorkflows/RequestedBy";
import StartedOn from "@/components/ApprovalWorkflows/StartedOn";
import Status from "@/components/ApprovalWorkflows/Status";
import WorkflowForm from "@/components/ApprovalWorkflows/WorkflowForm";
import Layout from "@/components/High/Layout";
import { ApprovalWorkflow, EditableApprovalWorkflow, EditableWorkflowStep, getUserTypeLabelShort } from "@/interfaces/approval.workflow";
import { CorporateUser, DeveloperUser, MasterCorporateUser, TeacherUser, User } from "@/interfaces/user";
import { sessionOptions } from "@/lib/session";
import { findBy, redirect, serialize } from "@/utils";
import { requestUser } from "@/utils/api";
import { getApprovalWorkflow } from "@/utils/approval.workflows.be";
import { getEntityWithRoles } from "@/utils/entities.be";
import { shouldRedirectHome } from "@/utils/navigation.disabled";
import { doesEntityAllow } from "@/utils/permissions";
import { getEntityUsers } from "@/utils/users.be";
import axios from "axios";
import { LayoutGroup, motion } from "framer-motion";
import { withIronSessionSsr } from "iron-session/next";
import Head from "next/head";
import Link from "next/link";
import { useEffect, useState } from "react";
import { BsChevronLeft } from "react-icons/bs";
import { toast, ToastContainer } from "react-toastify";

export const getServerSideProps = withIronSessionSsr(async ({ req, res, params }) => {
    const user = await requestUser(req, res);
    if (!user) return redirect("/login")

    if (shouldRedirectHome(user) || !["admin", "developer", "teacher", "corporate", "mastercorporate"].includes(user.type))
        return redirect("/")

    const { id } = params as { id: string };

    const workflow: ApprovalWorkflow | null = await getApprovalWorkflow("active-workflows", id);
    if (!workflow) return redirect("/approval-workflows");

    const entityWithRole = await getEntityWithRoles(workflow.entityId);
    if (!entityWithRole) return redirect("/approval-workflows");

    if (!doesEntityAllow(user, entityWithRole, "edit_workflow")) return redirect("/approval-workflows");

    return {
        props: serialize({
            user,
            workflow,
            workflowEntityApprovers: await getEntityUsers(workflow.entityId, undefined, { type: { $in: ["teacher", "corporate", "mastercorporate", "developer"] } }) as (TeacherUser | CorporateUser | MasterCorporateUser | DeveloperUser)[],
        }),
    };
}, sessionOptions);

interface Props {
    user: User,
    workflow: ApprovalWorkflow,
    workflowEntityApprovers: (TeacherUser | CorporateUser | MasterCorporateUser | DeveloperUser)[],
}

export default function Home({ user, workflow, workflowEntityApprovers }: Props) {
    const [updatedWorkflow, setUpdatedWorkflow] = useState<EditableApprovalWorkflow | null>(null);
    const [isLoading, setIsLoading] = useState<boolean>(false);

    useEffect(() => {
        const editableSteps: EditableWorkflowStep[] = workflow.steps.map(step => ({
            key: step.stepNumber + 999, // just making sure they are unique because new steps that users add will have key=3 key=4 etc
            stepType: step.stepType,
            stepNumber: step.stepNumber,
            completed: step.completed,
            completedBy: step.completedBy || undefined,
            completedDate: step.completedDate || undefined,
            assignees: step.assignees,
            firstStep: step.firstStep || false,
            finalStep: step.finalStep || false,
            onDelete: undefined,
        }));

        const editableWorkflow: EditableApprovalWorkflow = {
            ...workflow,
            id: workflow._id?.toString() ?? "",
            requester: user.id, // should it change to the editor?
            steps: editableSteps,
        };

        setUpdatedWorkflow(editableWorkflow);
    }, []);

    const handleSubmit = (e: React.FormEvent<HTMLFormElement>) => {
        e.preventDefault();
        setIsLoading(true);

        if (!updatedWorkflow) {
            setIsLoading(false);
            return;
        }

        for (const step of updatedWorkflow.steps) {
            if (step.assignees.every(x => !x)) {
                toast.warning("There is at least one empty step in the workflow.");
                setIsLoading(false);
                return;
            }
        }

        const filteredWorkflow: ApprovalWorkflow = {
            ...updatedWorkflow,
            steps: updatedWorkflow.steps.map(step => ({
                ...step,
                assignees: step.assignees.filter((assignee): assignee is string => assignee !== null && assignee !== undefined)
            }))
        };

        axios
            .put(`/api/approval-workflows/${updatedWorkflow.id}/edit`, filteredWorkflow)
            .then(() => {
                toast.success("Approval Workflow edited successfully.");
                setIsLoading(false);
            })
            .catch((reason) => {
                if (reason.response.status === 401) {
                    toast.error("Not logged in!");
                } else if (reason.response.status === 403) {
                    toast.error("You do not have permission to edit Approval Workflows!");
                } else {
                    toast.error("Something went wrong, please try again later.");
                }
                setIsLoading(false);
                console.log("Submitted Values:", filteredWorkflow);
                return;
            })
    };

    const onWorkflowChange = (updatedWorkflow: EditableApprovalWorkflow) => {
        setUpdatedWorkflow(updatedWorkflow);
    };

    return (
        <>
            <Head>
                <title> Edit Workflow | EnCoach</title>
                <meta
                    name="description"
                    content="A training platform for the IELTS exam provided by the Muscat Training Institute and developed by eCrop."
                />
                <meta name="viewport" content="width=device-width, initial-scale=1" />
                <link rel="icon" href="/favicon.ico" />
            </Head>
            <ToastContainer />
            <section className="flex items-center gap-2">
                <Link
                    href="/approval-workflows"
                    className="text-mti-purple hover:text-mti-purple-dark transition ease-in-out duration-300 text-xl">
                    <BsChevronLeft />
                </Link>
                <h1 className="text-2xl font-semibold">{workflow.name}</h1>
            </section>

            <section className="flex flex-col gap-6">
                <div className="flex flex-row gap-6">
                    <RequestedBy
                        prefix={getUserTypeLabelShort(user.type)}
                        name={user.name}
                        profileImage={user.profilePicture}
                    />
                    <StartedOn
                        date={workflow.startDate}
                    />
                    <Status
                        status={workflow.status}
                    />
                </div>
            </section>

            <form onSubmit={handleSubmit}>
                <LayoutGroup key={workflow.name}>
                    <motion.div
                        key="form"
                        initial={{ opacity: 0, y: -30 }}
                        animate={{ opacity: 1, y: 0 }}
                        exit={{ opacity: 0, x: 60 }}
                        transition={{ duration: 0.20 }}
                    >
                        {updatedWorkflow &&
                            <WorkflowForm
                                workflow={updatedWorkflow}
                                onWorkflowChange={onWorkflowChange}
                                entityApprovers={workflowEntityApprovers}
                                isLoading={isLoading}
                            />
                        }
                    </motion.div>
                </LayoutGroup>
            </form>
        </>
    );
}
