import React, { useEffect, useMemo } from "react";
import DataTable from "../../../../Layout/Dashboard/Table/DataTable";
import { useFilterState } from "../../../../Components/Utils/Filter/FilterState";
import { useFilterStateState } from "../../../../zustand/Filter";
import { useGetAllPermissions } from "../../../../api/Permissions";
import { useParams } from "react-router-dom";
import { ParamsEnum } from "../../../../enums/params";
import { useObjectToEdit } from "../../../../zustand/ObjectToEditState";
import { Form, Formik } from "formik";
import FormTable from "./FormTable";

const App: React.FC = () => {
  const { role_id } = useParams<ParamsEnum>();
  const { filterState } = useFilterState();
  const { Filter } = useFilterStateState();
  const name = Filter?.name;
  const sort_by = Filter?.sort_by;

  const Data = [
    "absence::delete",
    "absence::index",
    "absence::show",
    "absence::store",
    "absence::update",
    "admin::delete",
    "admin::index",
    "admin::show",
    "admin::update",
  ];

  /// time complexity O(n) -_-   
  const newArray: Array<{ name: any; [key: string]: boolean }> = [];
  const hashMap = new Map<string, number>();
  
  for (let i = 0; i < Data.length; i++) {
      const [permission, value] = Data[i].split("::");
            const existingIndex = hashMap.get(permission);

      if (existingIndex !== undefined) {
          newArray[existingIndex][value] = true;
          if(newArray[existingIndex]["index"] && newArray[existingIndex]["show"] && newArray[existingIndex]["store"] && newArray[existingIndex]["update"] && newArray[existingIndex]["delete"]){
            newArray[existingIndex]["ALL"] = true;
          }
      } else {
          const newObject = { name: permission, [value]: true } as any;
          newArray.push(newObject);
          hashMap.set(permission, newArray.length - 1); 
        
      }
  }
    console.log(newArray);
  

  const response = useGetAllPermissions({
    pagination: true,
    role_id,
    name,
    sort_by,
    ...filterState,
  });

  return (
   <Formik initialValues={newArray} onSubmit={()=>{}}>
    <Form>

    <FormTable  response={response} />
    <button>submit</button>
    </Form>
   </Formik>
  );
};

export default App;
