import { createFileRoute } from "@tanstack/react-router";
import { AppManagerTemplate } from "@/template/app-manager-template";
import { useQueryData } from "@/hooks/useQueryData";
import { useMutationData } from "@/hooks/useMutationData";
import { BASE_URL, API_ENDPOINTS } from "@/config/api";
import { toast } from "sonner";
import type { ColumnDef } from "@tanstack/react-table";
import { useState } from "react";

export const Route = createFileRoute("/_authenticated/apps/")({
  head: () => ({ meta: [{ title: "Quản lý phần mềm" }] }),
  component: AppsComponent,
});

type Version = {
  id: number;
  version: string;
  fileName: string;
  folderPath: string;
  updatedAt?: string;
};

function AppsComponent() {
  const { data, isLoading } = useQueryData({
    queryKey: ["software-version"],
    url: BASE_URL + API_ENDPOINTS.APP_VERSION.GET_SOFTWARE, // API lấy danh sách file MSI
  });

  const versionList: Version[] = Array.isArray(data)
    ? data
    : data
      ? [data]
      : [];
  const [table, setTable] = useState<any>();
  const uploadMutation = useMutationData<FormData>({
    url: BASE_URL + API_ENDPOINTS.APP_VERSION.UPLOAD,
    method: "POST",
    onSuccess: () => toast.success("Upload thành công!"),
    onError: () => toast.error("Upload thất bại!"),
  });

  const installMutation = useMutationData<{ msiFileIds: number[] }>({
    url: BASE_URL+ API_ENDPOINTS.DEVICE_COMM.DOWNLOAD_MSI,
    onSuccess: () => toast.success("Đã gửi yêu cầu cài đặt MSI!"),
    onError: () => toast.error("Gửi yêu cầu thất bại!"),
  });

  const columns: ColumnDef<Version>[] = [
    {
      id: "select",
      header: () => <span>Thêm vào danh sách yêu cầu</span>,
      cell: ({ row }) => (
        <input
          type="checkbox"
          checked={row.getIsSelected?.() ?? false}
          onChange={row.getToggleSelectedHandler?.()}
        />
      ),
      enableSorting: false,
      enableHiding: false,
    },
    { accessorKey: "version", header: "Phiên bản" },
    { accessorKey: "fileName", header: "Tên file" },
    { accessorKey: "folderPath", header: "Đường dẫn" },
    {
      accessorKey: "updatedAt",
      header: "Thời gian cập nhật",
      cell: ({ getValue }) =>
        getValue()
          ? new Date(getValue() as string).toLocaleString("vi-VN")
          : "N/A",
    },
  ];

  return (
    <AppManagerTemplate<Version>
      title="Quản lý phần mềm"
      description="Quản lý và gửi yêu cầu cài đặt phần mềm MSI"
      data={versionList}
      isLoading={isLoading}
      columns={columns}
      onUpload={(fd) => uploadMutation.mutateAsync(fd)} 
      onTableInit={setTable}
      onUpdate={() => {
        const selectedIds = table
          ?.getSelectedRowModel()
          .rows.map((row: any) => (row.original as Version).id);

        installMutation.mutateAsync({ msiFileIds: selectedIds });
      }}
      updateLoading={installMutation.isPending}
    />
  );
}
