import {
  createFileRoute,
  useParams,
  useNavigate,
} from "@tanstack/react-router";
import { useMemo } from "react";
import { useGetClientFolderStatus } from "@/hooks/queries";
import type { ClientFolderStatus } from "@/types/folder";
import FolderStatusTemplate from "@/template/folder-status-template";
import {
  createColumnHelper,
  getCoreRowModel,
  useReactTable,
} from "@tanstack/react-table";

export const Route = createFileRoute("/_auth/rooms/$roomName/folder-status/")({
  head: ({ params }) => ({
    meta: [{ title: `Trạng thái thư mục Setup phòng ${params.roomName}` }],
  }),
  loader: async ({ context, params }) => {
    context.breadcrumbs = [
      { title: "Danh sách phòng", path: "/rooms/" },
      { title: `Phòng ${params.roomName}`, path: `/rooms/${params.roomName}/` },
      { title: `Trạng thái thư mục Setup phòng ${params.roomName}`, path: `/rooms/${params.roomName}/folder-status/` },
    ];
  },
  component: RouteComponent,
});

function RouteComponent() {
  const { roomName } = useParams({
    from: "/_auth/rooms/$roomName/folder-status/",
  });
  const navigate = useNavigate();
  const { data: folderStatusList = [], isLoading } = useGetClientFolderStatus(
    roomName as string,
  );

  const columnHelper = createColumnHelper<ClientFolderStatus>();

  const columns = useMemo(
    () => [
      columnHelper.accessor("deviceId", {
        header: "Máy tính",
        cell: (info) => info.getValue() ?? "-",
      }),
      columnHelper.display({
        id: "missing",
        header: "Số lượng file thiếu",
        cell: (info) =>
          (info.row.original.missingFiles?.length ?? 0).toString(),
      }),
      columnHelper.display({
        id: "extra",
        header: "Số lượng file thừa",
        cell: (info) => (info.row.original.extraFiles?.length ?? 0).toString(),
      }),
      columnHelper.display({
        id: "current",
        header: "Số lượng file hiện tại",
        cell: (info) =>
          (info.row.original.currentFiles?.length ?? 0).toString(),
      }),
      columnHelper.accessor("updatedAt", {
        header: "Updated",
        cell: (info) => {
          const v = info.getValue();
          try {
            const d = new Date(v as string);
            return isNaN(d.getTime())
              ? (v as string)
              : d.toLocaleString("vi-VN");
          } catch {
            return v as string;
          }
        },
      }),
    ],
    [],
  );

  const table = useReactTable({
    data: folderStatusList ?? [],
    columns,
    getCoreRowModel: getCoreRowModel(),
  });

  return (
    <FolderStatusTemplate
      roomName={roomName as string}
      data={folderStatusList}
      isLoading={isLoading}
      onBack={() =>
        navigate({ to: "/rooms/$roomName/", params: { roomName } } as any)
      }
      table={table}
    />
  );
}
