import React, { memo, useEffect, useMemo, useState } from "react";
import { getManyByIds, GlobalContext } from "@/context/Global";
import { AuthContext } from "@/context/Auth";

function processNumberArray(value, options) {
  return value;
}
function processStringArray(value, options) {
  return value;
}

function addObjectArrayKey(value = [], options) {
  const result = value.reduce((prev, current, index) => {
    return prev + Number(current[options?.action?.key]);
  }, 0);

  return result;
}
const addListArrayKey = (value = [], options) =>
  value.map((item) => item[options?.action?.key]);

function buildReturnValue(item, options) {
  const { action } = options;
  const { init, join, key, table_key } = action;

  switch (init) {
    case "join":
      return table_key
        ? `${item[join][key]} - ${item[table_key]}`
        : item[join][key];
    case "table":
      return table_key
        ? `${item[table_key]} - ${item[join][key]}`
        : item[table_key];
    default:
      return item[join][key];
  }
}

async function fetchIDArrayJoinData(
  value = [],
  options,
  globalDispatch,
  authDispatch
) {
  if (!value.length) return [];
  try {
    const result = await getManyByIds(
      globalDispatch,
      authDispatch,
      options?.action?.table,
      value,
      options?.action?.join
    );
    if (!result?.error) {
      return result?.data?.map((item) =>
        item[options?.action?.join] ? buildReturnValue(item, options) : item?.id
      );
    }
  } catch (error) {
    console.error("Error fetching ID array join data:", error);
  }
  return value;
}

function processObjectArray(value, options) {
  if (!options?.action) return "";

  const processors = {
    add: addObjectArrayKey,
    list: addListArrayKey,
  };

  const processor = processors[options?.action?.operation];
  return processors ? processor(value, options) : "";
}

async function processIDArray(value, options, globalDispatch, authDispatch) {
  if (!options?.action) {
    return value;
  }

  const processors = {
    add: addObjectArrayKey,
    join: async (v, o) =>
      fetchIDArrayJoinData(v, o, globalDispatch, authDispatch),
  };

  const processor = processors[options?.action?.operation];
  return processor ? await processor(value, options) : "";
}

async function processJson(
  value,
  contentType,
  options,
  globalDispatch,
  authDispatch
) {
  if (!contentType) return "";

  const processors = {
    object_array: processObjectArray,
    id_array: (v, o) => processIDArray(v, o, globalDispatch, authDispatch),
    number_array: processNumberArray,
    string_array: processStringArray,
  };

  const processor = processors[contentType];
  return processor ? processor(value, options) : "";
}

async function processList(value, options, globalDispatch, authDispatch) {
  const [type, contentType] = options.listType.split("|");
  if (!type) return "";

  if (type === "json") {
    try {
      const parsedValue = JSON.parse(value);
      return processJson(
        parsedValue,
        contentType,
        options,
        globalDispatch,
        authDispatch
      );
    } catch (e) {
      console.error("Error parsing JSON:", e);
      return value;
    }
  }

  return value;
}

const MkdListTableRowListColumn = ({
  column,
  data,
  expandRow = false,
  currentTableData = [],
}) => {
  const { dispatch } = React.useContext(AuthContext);
  const {
    dispatch: globalDispatch,
    state: { columModel },
  } = React.useContext(GlobalContext);

  const [result, setResult] = useState(null);

  // const currentTableDataMemo = useMemo(
  //   () => JSON.stringify(currentTableData),
  //   [currentTableData]
  // );

  const getColumnListData = async (value, column) => {
    const result = await processList(value, column, globalDispatch, dispatch);
    if (!result) {
      setResult(() => []);
    }
    if (["string", "number"].includes(typeof result)) {
      setResult(() => [result]);
    }

    if (typeof result === "object" && Array.isArray(result)) {
      setResult(() => [...result]);
    }
  };

  // React.useEffect(() => {
  //   if (column?.list && data) {
  //     getColumnListData(data, column);
  //   }
  // }, [currentTableDataMemo]);

  return (
    <div className="flex items-center gap-[.25rem]">
      {data ? (
        <>
          {expandRow ? (
            <>
              {["string", "number"].includes(typeof data) ? (
                <span
                  className={`flex w-fit items-center justify-normal gap-[.25rem] rounded-[.375rem] border border-soft-200  p-[.25rem_.5rem_.25rem_.25rem] capitalize`}
                >
                  {data}
                </span>
              ) : typeof data === "object" && Array.isArray(data) ? (
                <>
                  {data.map((item, itemKey) => {
                    return (
                      <span
                        className={`flex w-fit items-center justify-normal gap-[.25rem] rounded-[.375rem] border border-soft-200  p-[.25rem_.5rem_.25rem_.25rem] capitalize`}
                        key={itemKey}
                      >
                        {item}
                      </span>
                    );
                  })}
                </>
              ) : null}
            </>
          ) : null}

          {!expandRow ? (
            <>
              {["string", "number"].includes(typeof data) ? (
                <span
                  className={`flex w-fit items-center justify-normal gap-[.25rem] rounded-[.375rem] border border-soft-200  p-[.25rem_.5rem_.25rem_.25rem] capitalize`}
                >
                  {data}
                </span>
              ) : typeof data === "object" && Array.isArray(data) ? (
                <>
                  {Array.from({
                    length:
                      data?.length > column?.limit
                        ? column?.limit
                        : data?.length,
                  }).map((_, itemKey) => {
                    return (
                      <span
                        className={`flex w-fit items-center justify-normal gap-[.25rem] rounded-[.375rem] border border-soft-200  p-[.25rem_.5rem_.25rem_.25rem] capitalize`}
                        key={itemKey}
                      >
                        {data[itemKey]}
                      </span>
                    );
                  })}
                  {data?.length > column?.limit ? (
                    <span
                      className={`flex w-fit items-center justify-normal gap-[.25rem] rounded-[.375rem] border border-soft-200  p-[.25rem_.5rem_.25rem_.25rem] capitalize`}
                    >
                      + {data.length - column?.limit}
                    </span>
                  ) : null}
                </>
              ) : null}
            </>
          ) : null}
        </>
      ) : null}
    </div>
  );
};

export default memo(MkdListTableRowListColumn);
