import Layout from "@/components/High/Layout";
import useUser from "@/hooks/useUser";
import { sessionOptions } from "@/lib/session";
import { mapBy, 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 WorkflowForm from "@/components/ApprovalWorkflows/WorkflowForm";
import Button from "@/components/Low/Button";
import Input from "@/components/Low/Input";
import { ApprovalWorkflow } from "@/interfaces/approval.workflow";
import { useEffect, useState } from "react";
import { MdFormatListBulletedAdd } from "react-icons/md";
import { CorporateUser, TeacherUser, User } from "@/interfaces/user";
import Select from "@/components/Low/Select";
import { getEntitiesUsers, getUsers, getUserWithEntity } from "@/utils/users.be";
import { getEntities } from "@/utils/entities.be";
import { Entity } from "@/interfaces/entity";

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 | undefined>(undefined);
    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 },
                { key: Date.now() + 1, completed: false, editView: true, stepType: "approval-by", stepNumber: 2, finalStep: true },
            ],
        };
        setWorkflows((prev) => [...prev, newWorkflow]);
        setSelectedWorkflowId(newId);
    };

    const onWorkflowChange = (updatedWorkflow: ApprovalWorkflow) => {
        console.log(updatedWorkflow);
        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;

        setWorkflows(prev => prev.filter(wf => wf.id !== id));
        if (selectedWorkflowId === id) {
            setSelectedWorkflowId(undefined);
        }
    };

    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}>
                    <section className="flex flex-col gap-0">
                        <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>

                        <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() === "" ? "New 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}
                                        onChange={(selectedEntity) => {
                                            if (selectedEntity?.value) {
                                                setEntityId(selectedEntity.value);
                                                const updatedWorkflow = {
                                                    ...currentWorkflow,
                                                    entityId: selectedEntity.value,
                                                };
                                                onWorkflowChange(updatedWorkflow);
                                            }
                                        }}
                                        isClearable
                                        placeholder="Entity..."
                                    />
                                    <Button
                                        color="purple"
                                        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>

                                <WorkflowForm
                                    workflow={currentWorkflow}
                                    onWorkflowChange={onWorkflowChange}
                                    entityTeachers={entityTeachers}
                                    entityCorporates={entityCorporates}
                                />
                            </>
                        )}
                    </form>
                </Layout>
            )}
        </>
    );
}
