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

type SendCommandRequest = { Command: string };
type SendCommandResponse = { status: string; message: string };

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

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

  // Mutation gửi lệnh
  const sendCommandMutation = useMutationData<
    SendCommandRequest,
    SendCommandResponse
  >({
    url: "", // sẽ set động theo roomName khi gọi
    method: "POST",
    onSuccess: (data) => {
      if (data.status === "OK") {
        toast.success("Gửi lệnh thành công!");
      } else {
        toast.error("Gửi lệnh thất bại!");
      }
    },
    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}
      rooms={roomData}
      onSubmit={(roomName, command) => {
        sendCommandMutation.mutateAsync({
          url: BASE_URL + API_ENDPOINTS.DEVICE_COMM.SEND_COMMAND(roomName),
          data: { Command: command },
        });
      }}
      submitLoading={sendCommandMutation.isPending}
    >
      {({ command, setCommand }) => (
        <ShellCommandForm
          command={command}
          onCommandChange={setCommand}
          disabled={sendCommandMutation.isPending}
        />
      )}
    </FormSubmitTemplate>
  );
}
