"use client"
import "@progress/kendo-theme-default/dist/all.css";
import { ProductOfProject } from "@/app/utils/interface/productOfProject";
import { Spreadsheet } from "@progress/kendo-react-spreadsheet";
import { Button, CustomAlertDialog, Dialog, DialogContent, DialogFooter, DialogHeader, DialogTitle, DialogTrigger, Form, FormComboboxInput, IconButtonWithTooltip, LoadingSpinner, TextButton } from "ikoncomponents";
import { Plus } from "lucide-react";
import React, { useEffect, useRef, useState } from "react";
import { addMultipleRows, getTaskTimeline, transformDataToSheet, transformDs1ToDs2, updateHeaderAndSubtotal } from "./spreadSheetFunctionality";
import { useForm } from "react-hook-form";
// import { transformDataToSheet, transformDs1ToDs2 } from "./spreadSheetFunctionality";
// import { Spreadsheet } from "@progress/kendo-react-spreadsheet";

import { Project } from "../../../types/project";
import ScheduleGanttShowComponent from "../scheduleTab/schedule_show_gantt_component";
import { getEmployees, getGrades, getRoles } from "@/app/utils/api/employeeDetails";
import { get } from "http";
import { createAllocation, deleteAllocation, updateAllocation } from "@/app/utils/api/productsResourceAllocation";
import ResourceModal from "./resourceModal";
import { de } from "date-fns/locale";

export let data = [
    {
        name: "Food Order",
        activeCell:"A3:A3",

frozenColumns: 5,
frozenRows: 1,
mergedCells: ['A2:E2', 'A5:D5', 'A6:E6', 'A9:D9', 'A10:E10', 'A13:D13', 'A14:E14', 'A17:D17', 'A18:E18', 'A21:D21', 'A22:E22', 'A25:D25', 'A26:E26', 'A29:D29', 'A30:E30', 'A33:D33', 'A34:D34'],
selection: "A3:A3",
        rows: [
            {
                cells: [
                    {
                        value: "ID", background: "rgb(167,214,255)", textAlign: "center", color: "rgb(0,62,117)"
                    },
                    {
                        value: "Product", background: "rgb(167,214,255)", textAlign: "center", color: "rgb(0,62,117)"
                    }
                ]
            },
            {
                cells: [
                    {
                        value: 216321, textAlign: "center", background: "rgb(229,243,255)", color: "rgb(0,62,117)"
                    },
                    {
                        value: "Calzone", background: "rgb(229,243,255)", color: "rgb(0,62,117)"
                    }
                ]
            },
            {
                cells: [
                    {
                        value: 546897, textAlign: "center", background: "rgb(229,243,255)", color: "rgb(0,62,117)"
                    },
                    {
                        value: "Margarita", background: "rgb(229,243,255)", color: "rgb(0,62,117)"
                    }
                ]
            },
            {
                cells: [
                    {
                        value: 456231, textAlign: "center", background: "rgb(229,243,255)", color: "rgb(0,62,117)"
                    },
                    {
                        value: "Pollo Formaggio", background: "rgb(229,243,255)", color: "rgb(0,62,117)"
                    }
                ]
            },
            {
                cells: [
                    {
                        value: 455873, textAlign: "center", background: "rgb(229,243,255)", color: "rgb(0,62,117)"
                    },
                    {
                        value: "Greek Salad", background: "rgb(229,243,255)", color: "rgb(0,62,117)"
                    }
                ]
            },
            {
                cells: [
                    {
                        value: 456892, textAlign: "center", background: "rgb(229,243,255)", color: "rgb(0,62,117)"
                    },
                    {
                        value: "Spinach and Blue Cheese", background: "rgb(229,243,255)", color: "rgb(0,62,117)"
                    }
                ]
            }

        ],
        columns: [
            {
                width: 100
            },
            {
                width: 100
            }
        ]
    }
];


export default function ResourceForm({ productData }: { productData: ProductOfProject | null }) {
    const spreadsheetRef = useRef<any>(null);
    const [refreshKey, setRefreshKey] = useState(0);
    const [isOpen, setIsOpen] = React.useState<boolean>(false);
    const [grantShow,setGrantShow] =useState(false)
    const [sheetData, setSheetData] = React.useState([]);

    const scheduleData = productData?.scheduleData;
    const [resourceData , setResourceData ] = useState([]);
    const [deleteResourceArr , setDeleteResourceArr] = useState([]);
    const taskData = sortByTaskStart(scheduleData?.task ?? [])
    const taskMonths = getTaskTimeline(taskData)

    const [empModal, setEmpModal] = useState(false);
    const [modalName, setModalName] = useState("");
    const [modalEmpData, setModalEmpData] = useState([])
    const [modalGradeData, setModalGradeData] = useState([])
    const [modaRoleData, setModalRoleData] = useState([])

    const [resourceModal, setResourceModal] = useState(false);
    const [loadSpinner, setLoadSpinner] = useState(true);
    const [showAlert, setShowAlert] = useState(false);
    const [alertMsg, setAlertMsg] = useState("")

    const [taskCells, setTaskCells] = useState(null)
    const [menuState, setMenuState] = useState({
        show: false,
        x: 0,
        y: 0,
    });

    const [employeeData, setEmployeeData] = useState([])
    const [roleData, setRoleData] = useState([])
    const [gradeData, setGradeData] = useState([])

    const form = useForm({
        defaultValues: {
            employee: "",
            grade: "",
            role: ""
        },
    })

    useEffect(() => {
        const fetch = async () => {
            const empData = await getEmployees();
            const item = [];
            item.push({ value: "Generic", label: "Generic" })
            empData.forEach(element => {
                item.push({ value: element.empId, label: element.name })
            });
            const grade = await getGrades();
            const roles = await getRoles();
            let modalData = []
            for (var i in grade) {
                modalData.push({ value: grade[i].grade, label: grade[i].grade })
            }
            setModalGradeData(modalData)
            modalData = []
            for (var i in roles) {
                modalData.push({ value: roles[i].role, label: roles[i].role })
            }
            setModalRoleData(modalData)
            setModalEmpData(item)

            setEmployeeData(empData)
            setRoleData(roles)
            setGradeData(grade)
        }
        fetch();
    }, [isOpen])

    const getRoleTitle = (role: string) => {
        ;
        return roleData?.find((e: any) => e.id == role)
    };

    const getGradeTitle = (grade: string) => {
        ;
        return gradeData.find((e: any) => e.id == grade)
    };

    function sortByTaskStart(tasks: any[]) {
        return tasks.sort((a, b) => {
            const dateA = new Date(a.taskStart).getTime();
            const dateB = new Date(b.taskStart).getTime();
            return dateA - dateB; // ascending order
        });
    }


    useEffect(() => {
        if (!isOpen) return;


        const interval = setInterval(() => {
            if (spreadsheetRef.current) {
                clearInterval(interval);

                let formData = null;
                if (productData.resourceDataWithAllocation.length > 0) {
                    formData = transformDataToSheet(productData.resourceDataWithAllocation)
                    let resData = {}
                    for (var i in formData) {
                        resData[i] = [];
                        for (var r in formData[i])
                            resData[i].push(formData[i][r].staff.split("-")[1].trim())
                    }

                    setResourceData(resData ? resData : {})
                    //    dsArr[0].rows = formData[0].rows

                }
                let dsArr = [generateResourcesDS(scheduleData?.task, taskMonths, formData ? formData : {})]
                setTaskCells(dsArr[0].taskCells)

                // buildSheet()
                // const sheet = spreadsheetRef.current.activeSheet();

                spreadsheetRef.current.fromJSON({ sheets: dsArr });
                const sheet = spreadsheetRef.current.activeSheet();
                sheet.range("A1:ZZ1000").enable(false);


                if (dsArr[0]?.rows) {
                    dsArr[0].rows.forEach((row, rowIndex) => {
                        if (row.cells) {
                            row.cells.forEach((cell, cellIndex) => {
                                // spreadsheet indexes are 1-based for the range string
                                const rowNum = rowIndex + 1;
                                const colLetter = columnName(cellIndex);

                                // Enable ONLY this specific cell
                                if (cellIndex > 4 && isRowBetweenTasks(rowNum, dsArr[0].taskCells) && cell.background == "#DAFBFF")
                                    sheet.range(`${colLetter}${rowNum}`).enable(true);
                            });
                        }
                    });
                }



                // setSheetData(dsArr)

            }
        }, 10);






        return () => clearInterval(interval);
    }, [isOpen, productData.resourceDataWithAllocation]);

    useEffect(() => {
        if (!isOpen) return;   // wait for dialog open

        // wait for Spreadsheet to mount
        const timer = setTimeout(() => {
            if (!spreadsheetRef.current) return;

            const widgetRoot = spreadsheetRef.current.element;

            if (!widgetRoot) return;

            const rightClickHandler = (e: any) => {
                const row = getSelectedRow(spreadsheetRef)
                if (!isRowBetweenTasks(row + 1, taskCells)) return;
                e.preventDefault();
                openContextMenu(e);
            };

            widgetRoot.addEventListener("contextmenu", rightClickHandler);

            // cleanup
            return () => widgetRoot.removeEventListener("contextmenu", rightClickHandler);
        }, 300); // small delay so Spreadsheet fully mounts

        return () => clearTimeout(timer);




    }, [isOpen, taskCells]);


    useEffect(() => {
        const handleKeyDown = (e) => {
            if (e.key === "Delete") {
                const spreadsheet = spreadsheetRef?.current;
                if (!spreadsheet) return;

                const sheet = spreadsheet.activeSheet();
                const row = getSelectedRow(spreadsheetRef)
                const range = sheet.selection();

                const startCol = range._ref.topLeft.col;
                const endCol = range._ref.bottomRight.col;
                if (startCol >= 1 && 4 > endCol) {
                    // Clear values from selected cells
                    range.value("");
                    taskMonths.forEach((t, i) => {
                        if (t.tasks.find((ta: any) => ta.taskName == sheet.range(row, 0).value())) {
                            const cell = sheet.range(row, i + 5);
                            cell.enable(false)
                            cell.background("#DAFBFF")
                            cell.value("")
                        }
                    })
                }
            }
        };

        window.addEventListener("keydown", handleKeyDown);

        return () => {
            window.removeEventListener("keydown", handleKeyDown);
        };
    }, [isOpen, taskCells]);

    useEffect(() => {
        setLoadSpinner(false)
    }, [taskCells])



    const onSpreadsheetReady = (widget: any) => {

        if (widget) {
            spreadsheetRef.current = widget;
            // console.log("Spreadsheet Ready:", spreadsheetRef?.current);
            // handleCellDoubleClick(widget.activeSheet())
        }


        // hideMenu()
        // setMenuState({ ...menuState, show: false })
    };


    const handleSelect = (e: any) => {
        hideMenu()
        const ss = spreadsheetRef.current;
        if (!ss) return;

        const sheet = ss.activeSheet();

        // Only single cell selection
        // if (e.range.topLeft().row !== e.range.bottomRight().row ||
        //     e.range.topLeft().col !== e.range.bottomRight().col) {
        //   return;
        // }

        const row = e.range.topLeft().row;
        const col = e.range.topLeft().col;




        const cellRef = `${columnName(col)}${row + 1}`;
        if (columnName(col) == "A") {
            const header = taskCells.find((t: any) => t.headerRow == (row + 1))

            if (header) {
                const notation = sheet.range(row, 0).value().replaceAll(header.headerTitle, "").trim()

                if (notation == "˄") {
                    sheet.range(row, 0).value("˅ " + header.headerTitle)
                    for (var i = row + 1; i < header.subtotalRow; i++) {
                        sheet.hideRow(i)
                    }
                }
                else {
                    sheet.range(row, 0).value("˄ " + header.headerTitle)
                    for (var i = row + 1; i < header.subtotalRow; i++) {
                        sheet.unhideRow(i)
                    }
                }



            }
        }
        if ((!(columnName(col) == "B") && !(columnName(col) == "C") && !(columnName(col) == "D")) || !isRowBetweenTasks(row + 1, taskCells)) {
            return;
        }

        if (sheet.range(row, col).value()) {
            if (sheet.range(row, col).value() == "Generic" || sheet.range(row, col - 1).value() == "Generic" || sheet.range(row, col - 2).value() == "Generic") {
                form.reset(columnName(col) == "B" ? { employee: "Generic" } : columnName(col) == "C" ? { grade: sheet.range(row, col).value() } : { role: sheet.range(row, col).value() })
                setModalName(columnName(col) == "B" ? "Employee" : columnName(col) == "C" ? "Grade" : "Role")

                setEmpModal(true);
                return;
            }
            const empId = sheet.range(row, col).value().split("-")[1].trim()
            form.reset({ employee: empId })

        }
        if ((columnName(col) == "B") || (columnName(col) == "C" && sheet.range(row, col - 1).value() == "Generic") || (columnName(col) == "D" && sheet.range(row, col - 2).value() == "Generic")) {
            setModalName(columnName(col) == "B" ? "Employee" : columnName(col) == "C" ? "Grade" : "Role")

            setEmpModal(true);


        }

    };





    function openContextMenu(e: any) {
        setMenuState({
            show: true,
            x: e.clientX - 80,
            y: e.clientY - 80,
        });
    }

    //   function for Excels 
    function getSelectedRow(spreadsheetRef: any) {
        const ss = spreadsheetRef.current;
        return ss.activeSheet().selection().topLeft().row;
    }

    async function addMultipleRowsInSheet(rows: number, tasks: {}) {
        const newTaskCellsWithHeader = await addMultipleRows(spreadsheetRef, rows, tasks, taskCells, taskMonths)
        setTaskCells(newTaskCellsWithHeader.taskCells)
    }


    async function addRowAbove(spreadsheetRef: any) {
        const ss = spreadsheetRef.current;
        const sheet = ss.activeSheet();
        const row = getSelectedRow(spreadsheetRef);
        sheet.insertRow(row);

        const data = (await ss.saveJSON())?.sheets;
        const rows = data[0].rows
        let newRows = []
        rows.forEach((element, i) => {
            if (i == row) {
                let elm = structuredClone(element)
                elm.index = row;
                const frm = elm.cells[4].formula;
                elm.cells[1].value = ""
                elm.cells[2].value = ""
                elm.cells[3].value = ""

                elm.cells[4].formula = frm?.replaceAll(i + 2 + "", i + 1 + "")
                // element.cells[4].formula = frm.replaceAll(row+1+"",row+2+"" )
                //  element.cells[5].validation?.from = element.cells[5].validation?.from.replaceAll(row+1+"",row+2+"" )
                for (var t in taskMonths) {
                    elm.cells[5 + parseInt(t)].value = ""
                    elm.cells[5 + parseInt(t)].enable = false
                }
                newRows.push(elm);
            }
            if (i >= row) {
                element.index = i + 1;

            }
            newRows.push(element);     // 👈 keep existing row
        });
        data[0].rows = newRows
        ss.fromJSON({ sheets: data })




        const totalCols = sheet._columns._count;
        let taskName = ""

        const newTaskCellsWithHeader = await updateHeaderAndSubtotal(taskCells, row)
        setTaskCells(newTaskCellsWithHeader.taskCells)


        setSubtotalCells(newTaskCellsWithHeader.taskCells, sheet)

        hideMenu();
    }

    async function addRowBelow(spreadsheetRef: any) {
        const ss = spreadsheetRef.current;
        const sheet = ss.activeSheet();
        const row = getSelectedRow(spreadsheetRef);


        // Insert row below
        sheet.insertRow(row + 1);


        const data = (await ss.saveJSON())?.sheets;
        const rows = data[0].rows
        let newRows = []
        rows.forEach((element, i) => {
            if (i == row) {
                let elm = structuredClone(element)
                const frm = element.cells[4].formula;
                element.cells[4].value = 0;
                element.cells[4].formula = frm?.replaceAll(i + 1 + "", i + 2 + "")
                // element.cells[4].formula = frm.replaceAll(row+1+"",row+2+"" )
                if (element.cells[5].validation)
                    element.cells[5].validation.from = element.cells[5].validation.from.replaceAll(row + 1 + "", row + 2 + "")

                for (var t in taskMonths) {
                    element.cells[5 + parseInt(t)].value = ""
                    element.cells[5 + parseInt(t)].enable = false
                }

                newRows.push(elm);
            }
            if (i >= row) {
                element.index = i + 1;
                if (i == row) {
                    element.cells[1].value = ""
                    element.cells[2].value = ""
                    element.cells[3].value = ""
                }

            }
            newRows.push(element);     // 👈 keep existing row
        });
        data[0].rows = newRows
        ss.fromJSON({ sheets: data })

        const totalCols = sheet._columns._count;

        const newTaskCellsWithHeader = await updateHeaderAndSubtotal(taskCells, row)
        setTaskCells(newTaskCellsWithHeader.taskCells)
        await setSubtotalCells(newTaskCellsWithHeader.taskCells)




        hideMenu();
    }

    async function setSubtotalCells(curTaskCells: []) {
        const sheet = spreadsheetRef.current.activeSheet();
        for (var i of curTaskCells) {

            const monthsArr = [4]
            taskMonths.forEach((t, i) => { monthsArr.push(i + 5) })
            // if(i.headerTitle = taskName){
            monthsArr.forEach((t) => {

                const cell = sheet.range(i.subtotalRow - 1, t);
                let sumF = ""
                for (let v = i.headerRow + 1; v < i.subtotalRow; v++) {
                    if (sumF == "") {
                        sumF += columnName(t) + v;
                        continue
                    }
                    sumF += "," + columnName(t) + v
                }
                // sumF.slice(sumF.lastIndexOf(","), sumF.length)
                // let formula = cell.formula();
                // formula = formula.replaceAll(formula.charAt(5),Number(formula.charAt(5))-1)
                cell.formula(`SUM(${sumF})`);


            })
            // const row = sheet.range(i.subtotalRow, c);
            // cells = .map(r => `E${r}`).join(",")
            // }
        }
    }

    async function deleteRow(spreadsheetRef: any) {
        const ss = spreadsheetRef.current;
        const sheet = ss.activeSheet();
        const row = getSelectedRow(spreadsheetRef);
        const coloumName = columnName(row)
        // /sheet.deleteRow(row);
        updateTaskCellsforDelete(row + 1)
        const sheetData = await ss.saveJSON();
        let newRows = []
        for (var i in sheetData.sheets[0].rows) {
            if (i == row) {
                setDeleteResourceArr([...deleteResourceArr, sheetData.sheets[0].rows[i].cells[0]?.textAlign])
                continue;
            }
            else if (i > row) {
                // Adjust row indices for rows below the deleted row
                sheetData.sheets[0].rows[i].index = parseInt(i) - 1;
                if (isRowBetweenTasks(i, taskCells))
                    sheetData.sheets[0].rows[i].cells[4].formula = sheetData.sheets[0].rows[i].cells[4].formula.replaceAll(parseInt(i) + 1, i)
            }
            newRows.push(sheetData.sheets[0].rows[i]);
        }
        let newSheetData = sheetData.sheets[0]
        newSheetData.mergedCells = updateMergeCells(row + 1, newSheetData.mergedCells)
        ss.fromJSON({ sheets: [{ ...sheetData.sheets[0], rows: newRows }] });
        setSubtotalCells(taskCells)
        hideMenu();

        setTotalCells()
    }

    const setTotalCells = () => {
        const sheet = spreadsheetRef.current.activeSheet();
        const totalRow = taskCells[taskCells.length - 1].subtotalRow
        let sum = []
        for (var t in taskCells) {
            sum.push(columnName(4) + taskCells[t].subtotalRow)
        }
        let cell = sheet.range(totalRow, 4)
        cell.formula(`SUM(${String(sum)})`)

        for (var m in taskMonths) {
            sum = []
            for (var t in taskCells) {
                sum.push(columnName(parseInt(m) + 5) + taskCells[t].subtotalRow)



            }
            let cell = sheet.range(totalRow, parseInt(m) + 5)
            cell.formula(`SUM(${String(sum)})`)

        }

    }

    const updateTaskCellsforDelete = (deletedRow: number) => {
        let newTaskCells = []
        let count = 0;
        taskCells.forEach((t: any) => {
            if (count) {
                t.headerRow = t.headerRow - 1;
                t.subtotalRow = t.subtotalRow - 1;
            }
            if (t.headerRow < deletedRow && t.subtotalRow > deletedRow) {
                t.subtotalRow = t.subtotalRow - 1;
                count = 1;
            }

            newTaskCells.push(t)
        })
        setTaskCells(newTaskCells);
    }

    function hideMenu() {
        setMenuState({ ...menuState, show: false });
    }

    const handleOnSubmit = (value: any) => {
        console.log(value)


        const sheet = spreadsheetRef.current.activeSheet();
        const row = getSelectedRow(spreadsheetRef)
        const taskName = sheet.range(row, 0).value();
        const empCells = sheet.range(row, 1);
        const roleCells = sheet.range(row, 3);
        const gradeCells = sheet.range(row, 2);


        //  else if(){

        //  } 
        if (value.employee == "Generic") {
            empCells.value("Generic")
            roleCells.enable(true)
            roleCells.value("")
            gradeCells.enable(true)
            gradeCells.value("")

            // form.reset({employee : ""}) 
        }
        else if (employeeData.find((t) => t.empId == value.employee)) {
            const empData = employeeData.find((t) => t.empId == value.employee)


            if (resourceData[taskName] && resourceData[taskName].includes(empData?.empId)) {
                setEmpModal(false)
                return;

            }
            else {
                if (!resourceData[taskName])
                    resourceData[taskName] = []

                const currRSE = empCells.value()
                if (!(currRSE === "Generic") && currRSE !== "")
                    resourceData[taskName].pop(currRSE.split("-")[1].trim())
                resourceData[taskName].push(empData?.empId)
            }
            empCells.value(empData?.name + " - " + empData?.empId)

            roleCells.value(getRoleTitle(empData?.role)?.role ? getRoleTitle(empData?.role)?.role : "N/A")


            gradeCells.value(getGradeTitle(empData?.grade)?.grade ? getGradeTitle(empData?.grade)?.grade : "N/A")
        }

        if (value.grade !== "" || value.role !== "") {
            gradeCells.value(value.grade)
            roleCells.value(value.role)
        }
        taskMonths.forEach((t, i) => {
            if (t.tasks.find((ta: any) => ta.taskName == sheet.range(row, 0).value())) {
                const cell = sheet.range(row, i + 5);
                cell.enable(true)
                cell.background("#DAFBFF")
            }
        })

        setEmpModal(false)
        form.reset({ employee: "" })
    }

    const saveResourceForm = async () => {
        const data = await spreadsheetRef.current.saveJSON();
        const resourceAllocation = transformDs1ToDs2(data.sheets);
        

       const allocationsWithIds = resourceAllocation.map((allocation: any) => {
            // 1. Find the matching original allocation (returns true/false for the match)
            const originalAllocation = productData.resourceDataWithAllocation?.find((orig: any) => 
                orig.taskId === Number(allocation.taskId) && orig.resourceId === allocation.resourceId
            );
            
            // 2. Return the new object for the map array
            return {
                ...allocation,
                id: originalAllocation?.id || allocation.id, // Fallback to current id if not found
            };
        });

        const updatedData = {
            ...productData,
            resourceDataWithAllocation: allocationsWithIds,
        };

        let allUpdateSuccess = true;
        for (const allocation of allocationsWithIds) {
            const allocationId = allocation.id || allocation.allocationId;
            delete allocation.id;
            if (!allocationId) {
                const response = await createAllocation(
                    productData.productIdentifier,
                    allocation
                );
                if (!response) {
                    console.error("Failed to update allocation", allocationId);
                    allUpdateSuccess = false;
                    continue;
                }
            }
            else{
             // Remove id from payload if API doesn't expect it
                const response = await updateAllocation(
                    productData.productIdentifier,
                    allocationId,
                    allocation
                );
                if (!response) {
                    console.error("Failed to update allocation", allocationId);
                    allUpdateSuccess = false;
                }
            }

        }
        if(deleteResourceArr.length > 0){
            for(var i in deleteResourceArr){
                const response = await deleteAllocation(
                    productData?.productIdentifier,
                    deleteResourceArr[i]
                );  
                if (response !== "") {
                    console.error("Failed to delete allocation", deleteResourceArr[i]);
                    allUpdateSuccess = false;
                    break;
                }
            }

        }

        if (allUpdateSuccess) {
            setIsOpen(false)
            window.location.reload(); // Refresh to get updated data from backend
        } else {
            alert("Some allocations failed to update. Please try again.");
        }
    }

    const onBeforeCellSave = (e) => {
        // 1. Get the range being edited
        const range = e.range;
        const sheet = e.sender.activeSheet();

        // 2. Get the new value being entered
        // In Kendo 'changing', e.value contains the proposed change


        // 3. Perform your custom logic / function call
        // const row = getSelectedRow(spreadsheetRef);
        // const col = range.col();
        const row = range.topLeft().row;
        const col = range.topLeft().col;

        if (col < 5) {
            return;
        }
        const cell = sheet.range(row, col)
        const newValue = cell.value();
        const colLetter = columnName(col); // Your helper function
        let available = 0;
        for (var i in taskMonths[col - 5].tasks) {
            if (taskMonths[col - 5].tasks[i].taskName == isRowBetweenWhichTasks(row + 1, taskCells)) {
                available = taskMonths[col - 5].tasks[i].taskDuration
            }
        }


        console.log(`User is trying to change ${colLetter}${row + 1} to: ${newValue}`);

        // Example: Logic check
        if (newValue > available && isRowBetweenTasks(row + 1, taskCells)) {
            // 4. STOP the event
            cell.value("")
            setAlertMsg(`Value ${newValue} exceeds available FTE of ${available}`)
            setShowAlert(true)
            // Optional: Show a UI hint or alert
            // alert(`Value ${newValue} exceeds available FTE of ${available}`);
        }
    };

    return (
        <Dialog open={isOpen} onOpenChange={setIsOpen}>
            <DialogTrigger>
                <IconButtonWithTooltip tooltipContent="Add Resource">
                    <Plus className="h-4 w-4" />
                </IconButtonWithTooltip>
            </DialogTrigger>
            <DialogContent className="sm:max-w-[90vw] w-full max-w-[1400px] overflow-auto  max-h-[100vh]">
                {loadSpinner ?
                    (
                        <LoadingSpinner visible={loadSpinner} />

                    )
                    :
                    (<>
                        <DialogHeader >
                            <DialogTitle className="text-xl font-bold">Resource</DialogTitle>
                        </DialogHeader>
                        <Button variant={"outline"} onClick={() => { setResourceModal(true) }}>
                            Add Resource
                        </Button>
                        {resourceModal && <ResourceModal setResourceModal={setResourceModal} tasks={scheduleData?.task} addMultipleRows={addMultipleRowsInSheet} />}
                        {grantShow && (
                            <div className="flex-1 min-w-0 overflow-hidden">
                                <ScheduleGanttShowComponent
                                    key={refreshKey}
                                    productIdentifier={productData?.projectIdentifier}
                                />
                            </div>
                        )} 
                        <div className="">
                            <Spreadsheet
                                onChange={onBeforeCellSave}
                                ref={onSpreadsheetReady}
                                style={{ width: "100%", height: "750px" }}
                                onSelect={handleSelect}
                                toolbar={false}


                            // defaultProps={{ select: addRow }}
                            // sheets={sheetData}
                            />
                            {menuState.show && (
                                <div className="absolute shadow-md border rounded z-50 bg-secondary"
                                    style={{ top: menuState.y, left: menuState.x }}>
                                    <div className="px-3 py-2 cursor-pointer"
                                        onClick={() => { addRowAbove(spreadsheetRef) }}>Add Row Above</div>
                                    <div className="px-3 py-2 cursor-pointer"
                                        onClick={() => { addRowBelow(spreadsheetRef) }}>Add Row Below</div>
                                    <div className="px-3 py-2  cursor-pointer"
                                        onClick={() => { deleteRow(spreadsheetRef) }}>Delete Row</div>
                                </div>
                            )}

                            {showAlert && (<CustomAlertDialog
                                title={alertMsg}
                                key="custom-alert-dialog"
                                description={""}
                                fontSize="text-base"
                                cancelText={"Ok"}
                                onCancel={() => setShowAlert(false)}

                            />)}



                            {/* {spreadsheetRef.current && <ContextMenuForResourceForm spreadsheetRef={spreadsheetRef}/>} */}
                        </div>
                        <style>
                            {`
                        .k-spreadsheet-action-bar {
                            display: none !important;
                        }

                        .k-spreadsheet-sheets-bar {
                            display: none !important;
                        }
                    `}
                        </style>
                        <div>
                            <Dialog open={empModal} onOpenChange={setEmpModal}>
                                <DialogContent>
                                    <DialogHeader>
                                        <DialogTitle>Add {modalName}</DialogTitle>
                                    </DialogHeader>
                                    <Form {...form}>
                                        <form
                                            onSubmit={form.handleSubmit(handleOnSubmit)}
                                            id="resource-form"
                                            className="space-y-6"
                                        >
                                            <FormComboboxInput
                                                formControl={form.control}
                                                placeholder={`Select ${modalName}`}
                                                name={modalName === "Employee" ? "employee" : modalName === "Grade" ? "grade" : "role"}
                                                items={modalName === "Employee" ? modalEmpData : modalName === "Grade" ? modalGradeData : modaRoleData}
                                            />
                                        </form>
                                    </Form>
                                    <DialogFooter>
                                        <TextButton type="submit" form="resource-form">
                                            Save
                                        </TextButton>
                                    </DialogFooter>
                                </DialogContent>
                            </Dialog>
                        </div>
                        <DialogFooter>
                            {!grantShow ? (<Button variant={"outline"} onClick={() => { setGrantShow(true) }}>
                                Show Grant Chat
                            </Button>) :
                                (<Button variant={"outline"} onClick={() => { setGrantShow(false) }}>
                                    Hide Grant Chat
                                </Button>)}
                            <Button variant={"outline"} onClick={() => { saveResourceForm() }}>
                                Save
                            </Button>
                        </DialogFooter>

                    </>)}
            </DialogContent>
        </Dialog>
    );
}

/**
 * generateResourcesDS(tasks)
 *
 * Input: tasks = Array of task objects with at least:
 *   { id, taskName, taskDuration, taskStart, taskEnd, taskColour? }
 *
 * Output: ds object matching the structure you provided (Resources sheet descriptor)
 */

function generateResourcesDS(tasks = [], taskMonths = [], resourceData = {}) {

    const BASE_COLS = 5; // A–F
    const rows = [];
    const mergedCells = [];
    let taskCells = [];
    const headerStyle = (v: string, align = "left") => ({
        value: v,
        color: "#000000",
        background: "#E9E9EA",
        enable: false,
        bold: false,
        wrap: true,
        textAlign: align,
        verticalAlign: "center",
        fontSize: 14
    });

    /* ----------------------------
        HEADER ROW
    -----------------------------*/
    rows.push({
        height: 25,
        cells: [
            headerStyle("Task Name"),
            headerStyle("Staff"),
            headerStyle("Grade"),
            headerStyle("Role"),
            headerStyle("Total FTE", "center")
        ]
    });

    // Add month headers (Dec, Jan, ...)
    taskMonths.forEach(m => {
        rows[0].cells.push(headerStyle(m.month, "center"));
    });

    let currentRow = 1;
    const subtotalRows = [];

    /* ----------------------------------
          LOOP TASK GROUPS
    -----------------------------------*/
    tasks.forEach(task => {

        /* -------------------
             GROUP ROW
        --------------------*/
        const groupRowIndex = ++currentRow;

        const groupCells = [
            {
                value: `˄ ${task.taskName}`,
                bold: true,
                color: "#0095D9",
                background: "#FFFFFF",
                enable: false,
                textAlign: "left",
                verticalAlign: "center",
                fontSize: 14
            },
            {enable : false , textAlign: `${task.id}`,},
        ];

        taskCells.push({ headerTitle: task.taskName, headerRow: currentRow })

        // Empty placeholders for merged cells (A–E)
        for (let i = 2; i < BASE_COLS; i++) groupCells.push({});

        // Add month header FTE for each month
        taskMonths.forEach(m => {
            const entry = m.tasks.find(t => t.taskName === task.taskName);
            if (entry) {
                groupCells.push({
                    value: Number(entry.taskDuration),
                    bold: true,
                    enable: false,
                    textAlign: "center",
                    verticalAlign: "center",
                    color: "#0095D9"
                });
            } else {
                groupCells.push({ enable: false });
            }
        });

        rows.push({ height: 25, cells: groupCells });
        mergedCells.push(`A${groupRowIndex}:E${groupRowIndex}`);

        /* -------------------
             DETAIL ROW
        --------------------*/
        const detailRowIndex = ++currentRow;
        const monthStartCol = BASE_COLS + 1;

        let detailCells = [
            { value: task.taskName, enable: false ,textAlign: ""},
            { value: "", background: "#bcf794" },
            { value: task.grade || "", background: "#bcf794", enable: false },
            {
                value: task.role || "",
                background: "#DAFBFF",
                enable: false
            },
            {
                // Column E = SUM of all month columns for this row
                formula: `SUM(F${detailRowIndex}:${columnName(monthStartCol + taskMonths.length - 1)}${detailRowIndex})`,
                enable: false,
                format: "0.00",
                textAlign: "center"
            }
        ];


        // Add month columns (editable)
        taskMonths.forEach((m, i) => {
            const entry = m.tasks.find(t => t.taskName === task.taskName);
            let count = 0
            if (!entry) {
                detailCells.push({ enable: false });
                count++;

            }
            else {


                const colLetter = columnName(BASE_COLS + count + i);
                const available = getAvailableFTEmonth(task, m);
                // const resData = ;
                const cell = {
                    enable: resourceData[task?.taskName]?.length > 0 ? true : false,
                    format: "0.00",
                    textAlign: "center",
                    value: null

                };
                // cell["validation"]={
                //     allowNulls: true,
                //     type: "reject",
                //     dataType: "custom",
                //     from: `OR(ISBLANK(${colLetter}${detailRowIndex}),AND(ISNUMBER(${colLetter}${detailRowIndex}),${colLetter}${detailRowIndex} >= 0,${colLetter}${detailRowIndex} <= ${available ?? 1}))`,
                //     titleTemplate: "Invalid value",
                //     messageTemplate: `Value cannot exceed available FTE (${available}).`
                // }
                detailCells.push(cell)
            }
        });
        detailCells.push({ value: "", enable: false })

        if (!resourceData[task?.taskName] && !resourceData[task?.taskName]?.length) {
            rows.push({ height: 25, cells: detailCells });
            ++currentRow
        }

        let count = 0;
        for (var t in resourceData[task?.taskName]) {
            const crrCell = structuredClone(detailCells)
            crrCell[0].textAlign = resourceData[task?.taskName][t].id

            crrCell[1].value = resourceData[task?.taskName][t].staff
            crrCell[2].value = resourceData[task?.taskName][t].grade
            crrCell[3].value = resourceData[task?.taskName][t].role

            for (var i = 5; i < detailCells.length; i++) {
                if (!detailCells[i].enable) {
                    continue;
                }
                const crtMonth = (taskMonths[i - 5]?.month).replace(" ", "_")

                if (resourceData[task?.taskName][t][crtMonth]) {
                    crrCell[i].value = resourceData[task?.taskName][t][crtMonth]
                    crrCell[i].enable = true
                    crrCell[i].background = "#DAFBFF"
                }
                crrCell[i].enable = true
                crrCell[i].background = "#DAFBFF"
            }
            if (count > 0) {
                crrCell[4].formula = crrCell[4].formula?.replaceAll((currentRow - count) + "", currentRow + "")
                // crrCell[5].validation.from = crrCell[5].validation.from.replaceAll((currentRow - count)+"", currentRow+"" )

            }

            rows.push({ height: 25, cells: crrCell });
            ++currentRow
            count++;
        }

        /* -------------------
             SUBTOTAL ROW
        --------------------*/
        const subtotalRowIndex = currentRow;
        subtotalRows.push(subtotalRowIndex);

        taskCells.forEach((ts) => {
            if (task.taskName == ts.headerTitle)
                ts["subtotalRow"] = currentRow
        })
        let sumF = ""
        if (resourceData[task?.taskName]) {
            sumF = "SUM("
            for (var i = detailRowIndex; i < currentRow; i++) {
                sumF += "E" + i;
                if (currentRow - 1 != i)
                    sumF += ","
            }
            sumF += ")"

        }
        const subtotalCells = [
            {
                value: `Subtotal - ${task.taskName}`,
                bold: true,
                background: "#E2F5FD",
                enable: false
            },
            {}, {}, {},
            {
                formula: sumF != "" ? sumF : `SUM(E${detailRowIndex})`,
                enable: false,
                format: "0.00",
                textAlign: "center"
            }
        ];

        // Month subtotals
        taskMonths.forEach((m, i) => {
            const entry = m.tasks.find(t => t.taskName === task.taskName);
            let count = 0
            if (!entry) {
                subtotalCells.push({ value: 0.00, enable: false, format: "0.00", textAlign: "center" });
                count++;
            }
            else {
                const col = columnName(BASE_COLS + count + i);
                let sumF = ""
                sumF = "SUM("
                for (var i = detailRowIndex; i < currentRow; i++) {
                    sumF += col + "" + i;
                    if (currentRow - 1 != i)
                        sumF += ","
                }
                sumF += ")"



                subtotalCells.push({
                    formula: sumF,
                    enable: false,
                    format: "0.00",
                    textAlign: "center"
                });
            }

        });

        rows.push({ height: 25, cells: subtotalCells });

        mergedCells.push(`A${subtotalRowIndex}:D${subtotalRowIndex}`);
    });

    /* -------------------
          GRAND TOTAL ROW
    --------------------*/
    const totalRowIndex = ++currentRow;

    const grandCells = [
        {
            value: "Total",
            bold: true,
            background: "#000000",
            color: "#FFFFFF",
            enable: false
        },
        {}, {}, {},
        {
            formula: `SUM(${subtotalRows.map(r => `E${r}`).join(",")})`,
            enable: false,
            textAlign: "center",
            format: "0.00",
            color: "#FFFFFF",
            background: "#000000"
        }
    ];

    // Month totals
    taskMonths.forEach((_, i) => {


        const col = columnName(BASE_COLS + i);
        grandCells.push({
            formula: `SUM(${subtotalRows.map(r => `${col}${r}`).join(",")})`,
            enable: false,
            textAlign: "center",
            color: "#FFFFFF",
            background: "#000000",
            format: "0.00"
        });
    });

    rows.push({ height: 25, cells: grandCells });
    mergedCells.push(`A${totalRowIndex}:D${totalRowIndex}`);

    /* -------------------
          RETURN DS
    --------------------*/
    const ds = {
        name: "Resources",
        activeCell: "A3:A3",
        selection: "A3:A3",
        rows,
        columns: [
            { width: 245 },
            { width: 250 },
            { width: 60 },
            { width: 200 },
            { width: 75 }
        ],
        frozenColumns: 5,
        frozenRows: 1,
        mergedCells,
        taskCells
    };

    // Add month column widths
    taskMonths.forEach(() => ds.columns.push({ width: 100 }));

    return ds;
}

/* ----------------------------------------
   Helpers
----------------------------------------*/

// Excel column letters
function columnName(n) {
    let s = "";
    while (n >= 0) {
        s = String.fromCharCode((n % 26) + 65) + s;
        n = Math.floor(n / 26) - 1;
    }
    return s;
}

// Get available FTE for validation
function getAvailableFTEmonth(task, monthObj) {
    const entry = monthObj.tasks.find(t => t.taskName === task.taskName);

    return entry ? Number(entry.taskDuration) : 0;
}

function isRowBetweenTasks(row: number, tasks: any) {
    return tasks.some(task => row > task.headerRow && row < task.subtotalRow);
}

function isRowBetweenWhichTasks(row: number, tasks: any) {
    const matchedTask = tasks.find(task =>
        row > task.headerRow && row < task.subtotalRow
    );

    // Return the title if found, otherwise return null or a default string
    return matchedTask ? matchedTask.headerTitle : null;
}

function updateMergeCells(deletedRow: number, mergeCells: string[]): string[] {
    const rangeRegex = /^([A-Z]+)(\d+):([A-Z]+)(\d+)$/;

    return mergeCells
        .map((range) => {
            const match = range.match(rangeRegex);
            if (!match) return null;

            const [, colStart, rowStartStr, colEnd, rowEndStr] = match;
            let rowStart = parseInt(rowStartStr, 10);
            let rowEnd = parseInt(rowEndStr, 10);

            // Case 1: The deleted row is ABOVE the merge range.
            // Move the whole range up by 1.
            if (deletedRow < rowStart) {
                return `${colStart}${rowStart - 1}:${colEnd}${rowEnd - 1}`;
            }

            // Case 2: The deleted row is WITHIN the merge range.
            // We return null to effectively "delete" this merge.
            if (deletedRow >= rowStart && deletedRow <= rowEnd) {
                return null;
            }

            // Case 3: The deleted row is BELOW the merge range.
            // No change needed.
            return range;
        })
        .filter((range): range is string => range !== null);
}

