import Layout from "@/components/High/Layout";
import { sessionOptions } from "@/lib/session";
import { redirect, serialize } from "@/utils";
import { requestUser } from "@/utils/api";
import { shouldRedirectHome } from "@/utils/navigation.disabled";
import { withIronSessionSsr } from "iron-session/next";
import Head from "next/head";
import Link from "next/link";
import { BsChevronLeft, BsTrash } from "react-icons/bs";
import { ToastContainer } from "react-toastify";
import { v4 as uuidv4 } from 'uuid';

import Tip from "@/components/ApprovalWorkflows/Tip";
import WorkflowForm from "@/components/ApprovalWorkflows/WorkflowForm";
import Button from "@/components/Low/Button";
import Input from "@/components/Low/Input";
import Select from "@/components/Low/Select";
import { ApprovalWorkflow } from "@/interfaces/approval.workflow";
import { Entity } from "@/interfaces/entity";
import { CorporateUser, TeacherUser, User } from "@/interfaces/user";
import { getEntities } from "@/utils/entities.be";
import { getEntitiesUsers } from "@/utils/users.be";
import { LayoutGroup, motion } from "framer-motion";
import { useEffect, useState } from "react";
import { MdFormatListBulletedAdd } from "react-icons/md";

export const getServerSideProps = withIronSessionSsr(async ({ req, res }) => {
    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 userEntitiesWithLabel = await getEntities(user.entities.map(entity => entity.id));

    return {
        props: serialize({
            user,
            userEntitiesWithLabel,
            userEntitiesTeachers: await getEntitiesUsers(userEntitiesWithLabel.map(entity => entity.id), { type: "teacher" }) as TeacherUser[],
            userEntitiesCorporates: await getEntitiesUsers(userEntitiesWithLabel.map(entity => entity.id), { type: "corporate" }) as CorporateUser[],
        }),
    };
}, sessionOptions);

interface Props {
    user: User,
    userEntitiesWithLabel: Entity[],
    userEntitiesTeachers: TeacherUser[],
    userEntitiesCorporates: CorporateUser[],
}

export default function Home({ user, userEntitiesWithLabel, userEntitiesTeachers, userEntitiesCorporates }: Props) {
    const [workflows, setWorkflows] = useState<ApprovalWorkflow[]>([]);
    const [selectedWorkflowId, setSelectedWorkflowId] = useState<string | undefined>(undefined);
    const [entityId, setEntityId] = useState<string | null | undefined>(null);
    const [entityTeachers, setEntityTeachers] = useState<TeacherUser[]>([]);
    const [entityCorporates, setEntityCorporates] = useState<CorporateUser[]>([]);

    useEffect(() => {
        if (entityId) {
            setEntityTeachers(
                userEntitiesTeachers.filter(teacher =>
                    teacher.entities.some(entity => entity.id === entityId)
                )
            );
            setEntityCorporates(
                userEntitiesCorporates.filter(corporate =>
                    corporate.entities.some(entity => entity.id === entityId)
                )
            );
        } else {
            setEntityTeachers([]);
            setEntityCorporates([]);
        }
    }, [entityId, userEntitiesTeachers, userEntitiesCorporates]);

    const currentWorkflow = workflows.find(wf => wf.id === selectedWorkflowId);

    const ENTITY_OPTIONS = userEntitiesWithLabel.map(entity => ({
        label: entity.label,
        value: entity.id,
        filter: (x: ApprovalWorkflow) => x.entityId === entity.id,
    }));

    const handleSubmit = (e: React.FormEvent<HTMLFormElement>) => {
        e.preventDefault();
        console.log("Form submitted! Values:", workflows);
    };

    const handleAddNewWorkflow = () => {
        const newId = uuidv4();
        const newWorkflow: ApprovalWorkflow = {
            id: newId,
            name: "",
            entityId: "",
            modules: [],
            status: "pending",
            steps: [
                { key: Date.now(), completed: false, editView: true, stepType: "form-intake", stepNumber: 1, firstStep: true, assignees: [null] },
                { key: Date.now() + 1, completed: false, editView: true, stepType: "approval-by", stepNumber: 2, finalStep: true, assignees: [null] },
            ],
        };
        setWorkflows((prev) => [...prev, newWorkflow]);
        setSelectedWorkflowId(newId);
    };

    const onWorkflowChange = (updatedWorkflow: ApprovalWorkflow) => {
        setWorkflows(prev =>
            prev.map(wf => (wf.id === updatedWorkflow.id ? updatedWorkflow : wf))
        );
    }

    const handleSelectWorkflow = (id: string) => {
        setSelectedWorkflowId(id);
    };

    const handleDeleteWorkflow = (id: string) => {
        if (!confirm(`Are you sure you want to delete this Approval Workflow?`)) return;

        const updatedWorkflows = workflows.filter(wf => wf.id !== id);

        setWorkflows(updatedWorkflows);

        if (selectedWorkflowId === id) {
            setSelectedWorkflowId(updatedWorkflows.find(wf => wf.id)?.id);
        }
    };

    const handleResetWorkflow = (id: string) => {
        setWorkflows(prev => prev.filter(wf => wf.id !== id));
        handleAddNewWorkflow();
    }

    return (
        <>
            <Head>
                <title> Configure Workflows | 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 />
            {user && (
                <Layout user={user} className="flex flex-col gap-6">
                    <section className="flex flex-col">
                        <div 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">{"Configure Approval Workflows"}</h1>
                        </div>
                    </section>

                    <section className="flex flex-row gap-6">

                        <Button
                            color="purple"
                            variant="solid"
                            onClick={handleAddNewWorkflow}
                            className="min-w-fit max-h-fit text-lg font-medium flex items-center gap-2 text-left"
                        >
                            <MdFormatListBulletedAdd className="size-6" />
                            Add New Workflow
                        </Button>

                        {workflows.length !== 0 && <div className="bg-gray-300 w-[1px]"></div>}

                        <div className="flex flex-wrap gap-2">
                            {workflows.map((workflow) => (
                                <Button
                                    key={workflow.id}
                                    color="purple"
                                    variant={
                                        selectedWorkflowId === workflow.id
                                            ? "solid"
                                            : "outline"
                                    }
                                    onClick={() => handleSelectWorkflow(workflow.id)}
                                    className="min-w-fit text-lg font-medium flex items-center gap-2 text-left"
                                >
                                    {workflow.name.trim() === "" ? "Workflow" : workflow.name}
                                </Button>

                            ))}
                        </div>
                    </section>

                    <form onSubmit={handleSubmit}>
                        {currentWorkflow && (
                            <>
                                <div className="mb-8 flex flex-row gap-6">
                                    <Input
                                        type="text"
                                        name={currentWorkflow.name}
                                        required={true}
                                        placeholder="Enter workflow name"
                                        value={currentWorkflow.name}
                                        onChange={(updatedName) => {
                                            const updatedWorkflow = {
                                                ...currentWorkflow,
                                                name: updatedName,
                                            };
                                            onWorkflowChange(updatedWorkflow);
                                        }}
                                    />
                                    <Select
                                        options={ENTITY_OPTIONS}
                                        value={
                                            currentWorkflow.entityId === ""
                                                ? null
                                                : ENTITY_OPTIONS.find(option => option.value === currentWorkflow.entityId)
                                        }
                                        onChange={(selectedEntity) => {
                                            if (!currentWorkflow.entityId && selectedEntity?.value) {
                                                setEntityId(selectedEntity.value);
                                                const updatedWorkflow = {
                                                    ...currentWorkflow,
                                                    entityId: selectedEntity.value,
                                                };
                                                onWorkflowChange(updatedWorkflow);
                                            } else {
                                                if (!confirm("Clearing or changing entity will reset this workflow. Are you sure you want to proceed?")) return;
                                                handleResetWorkflow(currentWorkflow.id);
                                            }
                                        }}
                                        isClearable
                                        placeholder="Entity..."
                                    />
                                    <Button
                                        color="red"
                                        variant="solid"
                                        onClick={() => handleDeleteWorkflow(currentWorkflow.id)}
                                        type="button"
                                        className="min-w-fit text-lg font-medium flex items-center gap-2 text-left"
                                    >
                                        Delete Workflow
                                        <BsTrash className="size-6" />
                                    </Button>
                                </div>

                                <LayoutGroup>
                                    {(!currentWorkflow.name || !currentWorkflow.entityId) && (
                                        <motion.div
                                            key={0}
                                            initial={{ opacity: 0, y: -20 }}
                                            animate={{ opacity: 1, y: 0 }}
                                            exit={{ opacity: 0, y: -20 }}
                                            transition={{ duration: 0.3 }}
                                        >
                                            <Tip text="Please fill workflow name and associated entity to start configuring workflow." />
                                        </motion.div>
                                    )}

                                    <motion.div
                                        key={1}
                                        initial={{ opacity: 0, y: -20 }}
                                        animate={{ opacity: 1, y: 0 }}
                                        exit={{ opacity: 0, y: -20 }}
                                        transition={{ duration: 0.3 }}
                                    >
                                        <WorkflowForm
                                            workflow={currentWorkflow}
                                            onWorkflowChange={onWorkflowChange}
                                            entityTeachers={entityTeachers}
                                            entityCorporates={entityCorporates}
                                        />
                                    </motion.div>
                                </LayoutGroup>
                            </>
                        )}
                    </form>
                </Layout>
            )}
        </>
    );
}
