import { createFileRoute } from "@tanstack/react-router";
import { FormSubmitTemplate } from "@/template/form-submit-template";
import { ShellCommandForm } from "@/components/command-form";
import { useMutationData } from "@/hooks/useMutationData";
import { BASE_URL, API_ENDPOINTS } from "@/config/api";
import { toast } from "sonner";

export const Route = createFileRoute("/_authenticated/command/")({
  head: () => ({ meta: [{ title: "Gửi lệnh CMD" }] }),
  component: CommandPage,
});

function CommandPage() {
  const sendCommandMutation = useMutationData<
    string,
    { success: boolean; output: string }
  >({
    url: BASE_URL + API_ENDPOINTS.DEVICE_COMM.SEND_COMMAND,
    method: "POST",
    onSuccess: (data) => {
      if (data.success) {
        toast.success("Lệnh đã được gửi thành công!");
      } else {
        toast.error("Lệnh không thể thực thi trên thiết bị!");
      }
    },
    onError: (error) => {
      console.error("Send command error:", error);
      toast.error("Gửi lệnh thất bại!");
    },
  });

  return (
    <FormSubmitTemplate
      title="CMD Command"
      description="Gửi lệnh shell xuống thiết bị để thực thi"
      isLoading={sendCommandMutation.isPending}
    >
      <ShellCommandForm
        onExecute={async (cmd: string) => {
          return await sendCommandMutation.mutateAsync({ data: cmd });
        }}
      />
    </FormSubmitTemplate>
  );
}
