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 type { AxiosProgressEvent } from "axios";
import { type Room } from "@/types/room";

type Version = {
  id?: string;
  version: string;
  fileName: string;
  folderPath: string;
  updatedAt?: string;
  requestUpdateAt?: 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,
  });

  // Lấy danh sách phòng
  const { data: roomData } = useQueryData({
    queryKey: ["rooms"],
    url: BASE_URL + API_ENDPOINTS.DEVICE_COMM.GET_ROOM_LIST,
  });

  // Map từ object sang string[]
  const rooms: string[] = Array.isArray(roomData)
    ? (roomData as Room[]).map((r) => r.name)
    : [];

  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",
    invalidate: [["agent-version"]],
    onSuccess: () => toast.success("Upload thành công!"),
    onError: (error) => {
      console.error("Upload error:", error);
      toast.error("Upload thất bại!");
    },
  });

  const updateMutation = useMutationData<void>({
    url: "", 
    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 handleUpload = async (
    fd: FormData,
    config?: { onUploadProgress?: (e: AxiosProgressEvent) => void }
  ) => {
    return uploadMutation.mutateAsync({
      data: fd,
      config,
    });
  };

  // Callback khi chọn phòng update
  const handleUpdate = async (roomName: string) => {
    return updateMutation.mutateAsync({
      url: BASE_URL + API_ENDPOINTS.DEVICE_COMM.UPDATE_AGENT(roomName),
      method: "POST",
      data: undefined,
    });
  };

  // Cột bảng
  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",
    },
    {
      accessorKey: "requestUpdateAt",
      header: "Thời gian yêu cầu 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={handleUpload}
      onUpdate={handleUpdate}
      updateLoading={updateMutation.isPending}
      rooms={rooms}
    />
  );
}
