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";

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

export const Route = createFileRoute("/_authenticated/agent/")({
  head: () => ({ meta: [{ title: "Quản lý Agent" }] }),
  component: AgentsPage,
});

function AgentsPage() {
  // Lấy danh sách version
  const { data, isLoading } = useQueryData({
    queryKey: ["agent-version"],
    url: BASE_URL + API_ENDPOINTS.APP_VERSION.GET_VERSION,
  });

  const versionList: Version[] = Array.isArray(data) ? data : data ? [data] : [];

  // Mutation upload
  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 updateMutation = useMutationData<void>({
    url: BASE_URL + API_ENDPOINTS.DEVICE_COMM.UPDATE_AGENT,
    method: "POST",
    onSuccess: () => toast.success("Đã gửi yêu cầu update!"),
    onError: () => toast.error("Gửi yêu cầu thất bại!"),
  });

  const columns: ColumnDef<Version>[] = [
    {
      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ý Agent"
      description="Quản lý và theo dõi các phiên bản Agent"
      data={versionList}
      isLoading={isLoading}
      columns={columns}
      onUpload={(fd) => uploadMutation.mutateAsync(fd)}
      onUpdate={() => updateMutation.mutateAsync()}
      updateLoading={updateMutation.isPending}
    />
  );
}
