import { useAddKeyToData, useColumns, Table } from ".";
import Loading from "../../../../../Components/DataState/Loading";
import EmptyData from "../../../../../Components/DataState/EmptyData";
import { useLocation, useParams } from "react-router-dom";
import { Student } from "../../../../../types/Item";
import React from "react";
import { useGetAllStudent } from "../../../../../api/student";
import { useObjectToEdit } from "../../../../../zustand/ObjectToEditState";
import usePagination from "../../../../../Layout/Dashboard/usePagination";
import { useTranslation } from "react-i18next";

const App: React.FC = () => {
  const { edu_class_id } = useParams();
  const [searchQuery, setSearchQuery] = React.useState<string>("");
  const location = useLocation();

  /// first_name
  React.useEffect(() => {
    const searchParams = new URLSearchParams(location?.search);
    setSearchQuery(searchParams?.get("name") || "");
    // console.log(searchQuery,"searchQuery");
  }, [location, searchQuery]);

  const { data, isLoading } = useGetAllStudent({
    name: searchQuery,
    edu_class_id: edu_class_id,
    pagination: true,
  });

  const students: Student[] = data?.data || [];
  const dataSource = useAddKeyToData(students);
  const columns = useColumns();
  const { set_object_to_edit, set_object_ids } = useObjectToEdit(
    (state) => state,
  );

  const getRowClassName = (record: any, index: number): string => {
    return index % 2 === 0 ? "even-row" : "odd-row";
  };

  const rowSelection = {
    onChange: (selectedRowKeys: React.Key[], selectedRows: any[]) => {
      set_object_ids(selectedRows);
    },
    getCheckboxProps: (record: any) => ({
      disabled: record.name === "Disabled User",
      name: record.name,
    }),
  };

  const { pagination, handlePageChange } = usePagination(data);

  function filterActiveRecords(dataSource: Student[]) {
    return dataSource?.filter(
      (item: Student) => item?.registration_record_status === "active",
    );
  }

  const [t] = useTranslation();
  return (
    <Table<Student>
      columns={columns}
      dataSource={filterActiveRecords(dataSource)}
      className="DataTable"
      rowClassName={(record, index) => getRowClassName(record, index)}
      loading={{
        spinning: isLoading,
        indicator: <Loading />,
        size: "large",
      }}
      locale={{
        emptyText: (
          <EmptyData
            loading={isLoading}
            header={t("Table.header")}
            info={t("Table.info")}
          />
        ),
      }}
      pagination={{
        ...pagination,
        onChange: handlePageChange,
      }}
      rowSelection={{
        type: "checkbox",
        ...rowSelection,
      }}
    />
  );
};

export default App;
