"use client";
import React from "react";
import {
  useReactTable,
  flexRender,
  getCoreRowModel,
  createColumnHelper,
} from "@tanstack/react-table";
import {
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableHeader,
  TableRow,
  TableFooter,
} from "@/components/ui/table";

import { getIconByName } from "@/Icons/icons";
import { useRouter } from "next/navigation";
import { encryptQuery, handleUpdateSubmission } from "@/apicalls/test";
import SingleTableHeader from "./SingleTableHeader";

interface TableComponentInterFace {
  restrictions: any;
  query: any;
  orderByValue: string;
  orderTypeValue: string;
}
const TableComponent: React.FC<TableComponentInterFace> = ({
  restrictions,
  query,
  orderByValue,
  orderTypeValue,
}) => {
  const router = useRouter();
  const [updateRow, setUpdateRow] = React.useState<any>(null);
  const [columns, setColumns] = React.useState<any[]>([]);
  const [orderBy, setOrderBy] = React.useState<"asc" | "desc">(
    orderByValue as "asc" | "desc"
  );
  const [orderColumn, setOrderColumn] = React.useState<string>(orderTypeValue);

  const columnHelper = createColumnHelper();
  const table = useReactTable({
    data: restrictions.table?.data?.data || [],
    columns,
    getCoreRowModel: getCoreRowModel(),
  });

  React.useEffect(() => {
    if (restrictions?.table?.headers) {
      setColumns(createColumnsFromValidations(restrictions.table.headers));
    }
  }, [restrictions.table.headers]);

  React.useEffect(() => {
    if (updateRow) {
      encryptQuery(updateRow).then((encryptData) => {
        router.push(`/building/update?q=${encryptData.replaceAll(" ", "+")}`);
      });
    }
  }, [updateRow]);

  function createColumnsFromValidations(headers: any) {
    const columns = Object.entries(headers).map(([key]: [string, any]) => {
      return columnHelper.accessor(key, {
        id: key,
        footer: headers[key],
        header: () => <span>{headers[key]}</span>,
        cell: (info) => <span>{info.getValue()}</span>,
      });
    });
    if (restrictions?.update) {
      columns.push(
        columnHelper.accessor("update", {
          id: "update",
          footer: "Update",
          header: () => <span>Update</span>,
          cell: () => (
            <div className="w-8 h-8 cursor-pointer">
              {restrictions?.update.icon &&
                React.createElement(getIconByName(restrictions?.update.icon))}
            </div>
          ),
        })
      );
    }
    return columns;
  }

  function changeOrderState(headerID: string) {
    console.log("changeOrderState", headerID, orderColumn, orderBy);
    if (orderColumn === headerID) {
      setOrderBy(orderBy === "asc" ? "desc" : "asc");
    } else {
      setOrderColumn(headerID);
      setOrderBy("asc");
    }
  }

  return (
    <>
      <div className="w-full min-w-full gap-4 mb-4">
        <h1>{JSON.stringify(updateRow)}</h1>
        <input
          hidden
          type="text"
          key="orderBy"
          name="orderBy"
          defaultValue={orderBy}
          readOnly
        />
        <input
          hidden
          type="text"
          key="orderType"
          name="orderType"
          defaultValue={orderColumn}
          readOnly
        />
        <Table className="px-8">
          <TableHeader>
            {table.getHeaderGroups().map((headerGroup) => (
              <TableRow key={headerGroup.id}>
                {headerGroup.headers.map((header) => (
                  <TableHead key={header.id} className="relative">
                    <SingleTableHeader
                      header={header}
                      orderBy={orderBy}
                      orderColumn={orderColumn}
                      changeOrderState={changeOrderState}
                    />
                  </TableHead>
                ))}
              </TableRow>
            ))}
          </TableHeader>
          <TableBody>
            {table.getRowModel().rows?.length ? (
              table.getRowModel().rows.map((row) => (
                <TableRow
                  key={row.id}
                  data-state={row.getIsSelected() && "selected"}
                >
                  {row.getVisibleCells().map((cell) =>
                    cell.column.id !== "update" ? (
                      <TableCell key={cell.id}>
                        {flexRender(
                          cell.column.columnDef.cell,
                          cell.getContext()
                        )}
                      </TableCell>
                    ) : (
                      <TableCell
                        key={cell.id}
                        onClick={() => setUpdateRow(row.original)}
                      >
                        {flexRender(
                          cell.column.columnDef.cell,
                          cell.getContext()
                        )}
                      </TableCell>
                    )
                  )}
                </TableRow>
              ))
            ) : (
              <TableRow>
                <TableCell
                  colSpan={columns.length}
                  className="h-24 text-center"
                >
                  No results.
                </TableCell>
              </TableRow>
            )}
          </TableBody>
          <TableFooter>
            {table.getFooterGroups().map((footerGroup) => (
              <TableRow key={footerGroup.id}>
                {footerGroup.headers.map(
                  (footer) =>
                    footer.id !== "update" && (
                      <TableCell key={footer.id}>
                        {footer.isPlaceholder ? null : (
                          <input
                            key={footer.id}
                            name={footer.id}
                            type="text"
                            className="w-full text-center border p-1 text-sm h-8"
                            placeholder={`${String(
                              footer.column.columnDef.footer
                            )}`}
                            defaultValue={query[footer.id] || ""}
                          />
                        )}
                      </TableCell>
                    )
                )}
              </TableRow>
            ))}
          </TableFooter>
        </Table>
      </div>
    </>
  );
};

export default TableComponent;
