import { useState, useEffect, useRef } from "react";
import debounce from "lodash/debounce";
import CardGridWidgetView from "./CardGridWidgetView";
import { CardDataState, InfiniteCardProps } from "./type";
import { CompositeFilterDescriptor } from "@progress/kendo-data-query";
import _ from "lodash";

export const initialLocalFilters: CompositeFilterDescriptor = {
  logic: "and",
  filters: [],
};
let needDataConcat = false;
const CardGridWidget = (props: InfiniteCardProps) => {
  const [hasMore, setHasMore] = useState(true);
  const [activeColumns, setActiveColumns] = useState<any[]>([]);
  const [baseData, setBaseData] = useState<CardDataState>({
    records: [],
    total: 0,
  });

  const [page, setPage] = useState(1);

  const scrollContainerRef = useRef<HTMLElement>(null);

  useEffect(() => {
    const defaultColumns = [...(props.columns ?? [])].sort(
      (a, b) => (a.order ?? 0) - (b.order ?? 0)
    );
    const updatedUiElementGroupData = {
      ...props.uiElementGroupData,
      processing: false,
      localSearch: initialLocalFilters,
      sort: props.sortConfig?.defaultSortFields ?? [],
      defaultSort: props.sortConfig?.defaultSortFields ?? [],
      globalFilters: props.filterConfig?.defaultFilterCriteria,
      defaultGroups: props.groupConfig?.defaultGroupFields ?? [],
      pagination: props.paginationConfig?.defaultPagination,
      defaultPagination: props.paginationConfig?.defaultPagination,
      defaultColumns,
      lazyLoad: props.lazyLoading,
      enableDataLoading: false,
    };

    props.onModelUpdate?.(
      null,
      props.config.uiElementGroupId,
      _.cloneDeep(updatedUiElementGroupData)
    );
    return () => {
      props?.onModelUpdate?.(null, props.screenDataField ?? "", {
        records: [],
        total: 0,
      });
    };
  }, []);

  useEffect(() => {
    if (needDataConcat) {
      needDataConcat = false;
      setBaseData((prevData) => ({
        records: [...prevData.records, ...(props.value?.records ?? [])],
        total: props.lazyLoading
          ? props.value?.total ?? 0
          : props.value?.records?.length ?? 0,
      }));
    } else {
      setBaseData((prevData) => ({
        records: props.value?.records ?? [],
        total: props.lazyLoading
          ? props.value?.total ?? 0
          : props.value?.records?.length ?? 0,
      }));
    }
  }, [JSON.stringify(props.value)]);

  useEffect(() => {
    let columns = [];
    const chooserColumns =
      props?.uiElementGroupData?.setting?.columnChooser?.appliedColumns;

    if (chooserColumns?.length) {
      chooserColumns?.map((c: any) => {
        const column = _.cloneDeep(
          props.columns?.find((column: any) => c.id === column.id)
        );

        if (c.includeInCard && column) {
          column.locked = c.isFreezed;
          column.order = c.order;
          column.selected = c.selected;
          if (c.width) {
            column.width = c.width;
          }
          columns.push(column);
        }
      });
    } else {
      columns =
        props?.uiElementGroupData?.defaultColumns?.filter(
          (column: any) => column.selected === true
        ) ?? [];
    }

    const sortedColumns = columns?.sort((a: any, b: any) => a.order - b.order);
    setActiveColumns(sortedColumns);
  }, [
    JSON.stringify(props?.uiElementGroupData?.defaultColumns),
    JSON.stringify(
      props?.uiElementGroupData?.setting?.columnChooser?.appliedColumns
    ),
  ]);

  useEffect(() => {
    if (
      props?.uiElementGroupData?.processing === false &&
      props.onScreenDataLoad
    ) {
      props.onScreenDataLoad?.(resultHandler);
    }
  }, [
    JSON.stringify(props?.uiElementGroupData?.pagination),
    props?.uiElementGroupData?.processing,
  ]);

  useEffect(() => {
    if (page > 1) {
      let uiElementGroupData = props?.uiElementGroupData ?? {};

      uiElementGroupData = {
        ...uiElementGroupData,
        pagination: {
          ...uiElementGroupData.pagination,
          skip:
            (page - 1) *
            (uiElementGroupData?.pagination?.take ??
              uiElementGroupData?.defaultPagination?.take ??
              0),
        },
      };
      needDataConcat = true;
      props?.onModelUpdate?.(
        null,
        props?.config?.uiElementGroupId,
        uiElementGroupData
      );
      /* if (scrollContainerRef.current) {
        scrollContainerRef.current?.scrollTo({
          top: 0,
          behavior: "smooth",
        });
      } */
    }
  }, [page]);

  useEffect(() => {
    if (baseData.total <= baseData.records.length && baseData.total > 0) {
      setHasMore(false);
    } else {
      setHasMore(true);
    }
  }, [JSON.stringify(baseData.records)]);

  useEffect(() => {
    const container: any = scrollContainerRef.current;
    container?.addEventListener("scroll", handleScroll);
    return () => container?.removeEventListener("scroll", handleScroll);
  }, [hasMore]);

  const resultHandler = (response: any) => {
    props.onModelUpdate?.(null, props.screenDataField ?? "", response);
  };

  const handleScroll = debounce(() => {
    const container: any = scrollContainerRef.current;

    if (
      container?.scrollTop + container?.clientHeight <
        container?.scrollHeight ||
      !hasMore
    )
      return;

    setPage((prevPage) => prevPage + 1);
  }, 200);

  const handleClick = (cellProps: any, e: any) => {
    props.navigate && props.navigate(null, cellProps.dataItem.id);
  };

  return (
    <section
      ref={scrollContainerRef}
      className={`prc-infinite-card-section ${
        props.widgetStyle?.className || ""
      }`}
      id={props.widgetStyle?.id || ""}
      style={props.widgetStyle?.inline || {}}
    >
      {baseData?.total > 0 && (
        <h3 className="prc-infinite-card__paginator">
          1 - {baseData?.records?.length} of {baseData?.total} items
        </h3>
      )}
      <div className={`prc-infinite-card-container`}>
        {baseData?.records?.map((record, index) => (
          <CardGridWidgetView
            key={index}
            record={record}
            headerField={props.headerField}
            columns={activeColumns}
            handleClick={handleClick}
          />
        ))}
      </div>
      <section className="prc-infinite-card__footer">
        {!hasMore && baseData?.total > 0 && <b>No more records to load!</b>}
      </section>
    </section>
  );
};

export default CardGridWidget;
