import React, { useContext, useEffect, useMemo } from "react";
import { HolderOutlined } from "@ant-design/icons";
import type { DragEndEvent } from "@dnd-kit/core";
import { DndContext } from "@dnd-kit/core";
import type { SyntheticListenerMap } from "@dnd-kit/core/dist/hooks/utilities";
import { restrictToVerticalAxis } from "@dnd-kit/modifiers";
import {
  arrayMove,
  SortableContext,
  useSortable,
  verticalListSortingStrategy,
} from "@dnd-kit/sortable";
import { CSS } from "@dnd-kit/utilities";
import { Button, Table } from "antd";
import { useParams } from "react-router-dom";
import { ParamsEnum } from "../../enums/params";
import { useGetAllUnit, useUpdateUnitOrder } from "../../api/unit";
import Loading from "../../Components/DataState/Loading";
import EmptyData from "../../Components/DataState/EmptyData";
import { useTranslation } from "react-i18next";
import { useColumns } from "./useTableColumns";

interface DataType {
  id: string; // Unique identifier for each row
  order: number;
  name: string;
  age: number;
  address: string;
}

interface RowContextProps {
  setActivatorNodeRef?: (element: HTMLElement | null) => void;
  listeners?: SyntheticListenerMap;
}

const RowContext = React.createContext<RowContextProps>({});

export const DragHandleUnit: React.FC = () => {
  const { setActivatorNodeRef, listeners } = useContext(RowContext);
  return (
    <Button
      type="text"
      size="small"
      icon={<HolderOutlined />}
      style={{ cursor: "move" }}
      ref={setActivatorNodeRef}
      {...listeners}
    />
  );
};


interface RowProps extends React.HTMLAttributes<HTMLTableRowElement> {
  "data-row-key": string;
}

const Row: React.FC<RowProps> = (props) => {
  const {
    attributes,
    listeners,
    setNodeRef,
    setActivatorNodeRef,
    transform,
    transition,
    isDragging,
  } = useSortable({ id: props["data-row-key"] });

  const style: React.CSSProperties = {
    ...props.style,
    transform: CSS.Translate.toString(transform),
    transition,
    ...(isDragging ? { position: "relative", zIndex: 9999 } : {}),
  };

  const contextValue = useMemo<RowContextProps>(
    () => ({ setActivatorNodeRef, listeners }),
    [setActivatorNodeRef, listeners],
  );

  return (
    <RowContext.Provider value={contextValue}>
      <tr {...props} ref={setNodeRef} style={style} {...attributes} />
    </RowContext.Provider>
  );
};

const DrapableTable: React.FC = () => {
  const { subject_id } = useParams<ParamsEnum>();
  const response = useGetAllUnit({ subject_id: subject_id, pagination: false });

  // Assuming the response contains a unique id for each item
  const data =
    response?.data?.data?.map((item: any, index: number) => ({
      id: item.id, // Ensure this is a unique identifier
      order: index + 1, // Assign order based on index
      ...item
    })) ?? [];

  const [dataSource, setDataSource] = React.useState<DataType[]>(data);

  useEffect(() => {
    // Update dataSource when the fetched data changes
    const sortedData = data.sort((a: any, b: any) => a.order - b.order);
    setDataSource(sortedData);
  }, [response?.data?.data]);

    const {mutate:orderUnit} = useUpdateUnitOrder({},{
      retry:false
    })
  const onDragEnd = ({ active, over }: DragEndEvent) => {
    if (active.id !== over?.id) {
      setDataSource((prevState) => {
        const activeIndex = prevState.findIndex(
          (record) => record.id === active.id,
        );
       
        const overIndex = prevState.findIndex(
           //@ts-ignore
          (record) => record.id === over.id,
        );

        // Move the items in the array
        const newState = arrayMove(prevState, activeIndex, overIndex);
          const orderedNewState = newState.map((item, index) => ({
            ...item,
            order: index + 1, // Update the order based on the new index
          }));
        // Update the order based on the new positions
        const orderedNewStateWithNewChape = orderedNewState?.map((item:any)=>{
          return {
            "unit_id":item?.id,
            "order":item?.order
          }
        })
        orderUnit({units: orderedNewStateWithNewChape, _method:"PUT"})
        return orderedNewState
      });

        
    }
  };

  const getRowClassName = (record: any, index: number): string => {
    return index % 2 === 0 ? "even-row" : "odd-row";
  };
  const isRefetching = response?.isRefetching;
  const [t] = useTranslation()
  const columns = useColumns();
  const sortedDataSource = dataSource.sort((a, b) => a.order - b.order) ;
  console.log(sortedDataSource,"sortedDataSource");
  
  return (
    <DndContext modifiers={[restrictToVerticalAxis]} onDragEnd={onDragEnd}>
      <SortableContext
        items={dataSource.map((i) => i.id)}
        strategy={verticalListSortingStrategy}
      >
        <Table
          rowKey="id"
          components={{ body: { row: Row } }}
           //@ts-ignore
          columns={columns}
          dataSource={sortedDataSource} 
          pagination={false}
        rowClassName={(record, index) => getRowClassName(record, index)}
      className="DataTable"
      loading={{
        spinning: response?.isLoading || isRefetching,
        indicator: <Loading />,
        size: "large",
      }}
      locale={{
        emptyText: (
          <EmptyData
            loading={response?.isLoading}
            header={t("Table.header")}
            info={t("Table.info")}
          />
        ),
      }}
        />
      </SortableContext>
    </DndContext>
  );
};

export default DrapableTable;
