import { WorkflowStep } from "@/interfaces/approval.workflow";
import Option from "@/interfaces/option";
import { CorporateUser, TeacherUser } from "@/interfaces/user";
import { useEffect, useMemo, useState } from "react";
import { AiOutlineUserAdd } from "react-icons/ai";
import { BsTrash } from "react-icons/bs";
import { LuGripHorizontal } from "react-icons/lu";
import WorkflowStepNumber from "./WorkflowStepNumber";
import WorkflowStepSelects from "./WorkflowStepSelects";
import Image from "next/image";

interface Props extends WorkflowStep {
    entityTeachers: TeacherUser[];
    entityCorporates: CorporateUser[];
    onSelectChange: (numberOfSelects: number, index: number, value: Option | null) => void;
}

export default function WorkflowEditableStepComponent({
    stepNumber,
    assignees = [null],
    finalStep,
    onDelete,
    onSelectChange,
    entityTeachers,
    entityCorporates,
}: Props) {

    const [selects, setSelects] = useState<(Option | null | undefined)[]>([null]);

    const teacherOptions: Option[] = useMemo(() => 
        entityTeachers
            .map((teacher) => ({
                value: teacher.id,
                label: teacher.name,
                icon: () => <Image src={teacher.profilePicture} alt={teacher.name} />
            }))
            .sort((a, b) => a.label.localeCompare(b.label)),
        [entityTeachers]
    );

    const corporateOptions: Option[] = useMemo(() => 
        entityCorporates
            .map((corporate) => ({
                value: corporate.id,
                label: corporate.name,
                icon: () => <Image src={corporate.profilePicture} alt={corporate.name} />
            }))
            .sort((a, b) => a.label.localeCompare(b.label)),
        [entityCorporates]
    );

    const allOptions = useMemo(() => [...teacherOptions, ...corporateOptions], [teacherOptions, corporateOptions]);

    useEffect(() => {
        if (assignees && assignees.length > 0) {
            const initialSelects = assignees.map((assignee) =>
                typeof assignee === 'string' ? allOptions.find(opt => opt.value === assignee) || null : null
            );
    
            setSelects((prevSelects) => {
                // This is needed to avoid unnecessary re-renders which can cause warning of a child component being re-rendered while parent is in the midle of also re-rendering.
                const areEqual = initialSelects.length === prevSelects.length && initialSelects.every((option, idx) => option?.value === prevSelects[idx]?.value);
                
                if (!areEqual) {
                    return initialSelects;
                }
                return prevSelects;
            });
        } 
    }, [assignees, allOptions]);

    const selectedValues = useMemo(() => 
        selects.filter((opt): opt is Option => !!opt).map(opt => opt.value),
        [selects]
    );

    const availableTeacherOptions = useMemo(() => 
        teacherOptions.filter(opt => !selectedValues.includes(opt.value)),
        [teacherOptions, selectedValues]
    );

    const availableCorporateOptions = useMemo(() => 
        corporateOptions.filter(opt => !selectedValues.includes(opt.value)),
        [corporateOptions, selectedValues]
    );

    const handleAddSelectComponent = () => {
        setSelects((prev) => {
            const updated = [...prev, null];
            onSelectChange(updated.length, updated.length - 1, null);
            return updated;
        });
    };

    const handleSelectChangeAt = (numberOfSelects: number, index: number, option: Option | null) => {
        const updated = [...selects];
        updated[index] = option;
        setSelects(updated);
        onSelectChange(numberOfSelects, index, option);
    };

    return (
        <div className="flex w-full">
            <div className="flex flex-col items-center">
                <WorkflowStepNumber stepNumber={stepNumber} />

                {/* Vertical Bar connecting steps */}
                {!finalStep && (
                    <div className="w-1 h-full min-h-10 bg-mti-purple-dark"></div>
                )}
            </div>

            {stepNumber !== 1 && !finalStep
                ? <LuGripHorizontal className="ml-3 mt-2 cursor-grab active:cursor-grabbing min-w-[25px] min-h-[25px]" />
                : <div className="ml-3 mt-2" style={{ width: 25, height: 25 }}></div>
            }

            <div className="ml-10 mb-12">
                <WorkflowStepSelects
                    teachers={availableTeacherOptions}
                    corporates={availableCorporateOptions}
                    selects={selects}
                    placeholder={stepNumber === 1 ? "Form Intake By:" : "Approval By:"}
                    onSelectChange={handleSelectChangeAt}
                />
            </div>

            <div className="flex flex-row items-start mt-1.5 ml-3">
                <button
                    type="button"
                    onClick={handleAddSelectComponent}
                    className="cursor-pointer"
                >
                    <AiOutlineUserAdd className="size-7 hover:text-mti-purple-light transition ease-in-out duration-300" />
                </button>
                {stepNumber !== 1 && !finalStep && (
                    <button
                        className="cursor-pointer"
                        onClick={onDelete}
                        type="button"
                    >
                        <BsTrash className="size-6 mt-0.5 ml-3 hover:text-mti-purple-light transition ease-in-out duration-300" />
                    </button>
                )}
            </div>
        </div>

    );
};