"use client";
import { postData } from "@/utils/fetch";
import { zodResolver } from "@hookform/resolvers/zod";
import { useMutation } from "@tanstack/react-query";
import dynamic from "next/dynamic";
import { FC, useRef, useState } from "react";
import { FormProvider, useForm } from "react-hook-form";
import { toast } from "react-toastify";
import Spinner from "../spinner";
import { fundSchema } from "../forms/schema/fund";
const DropdownList = dynamic(() => import("../common/Dropdown"));

const CommandList: FC = () => {
  const [network, setNetwork] = useState<any>(null);
  const [command, setCommand] = useState<any>("");
  const bankForm = useForm<any>({
    resolver: zodResolver(fundSchema),
    mode: "onChange",
    defaultValues: {},
  });

  const inputRef = useRef<HTMLInputElement>(null);

  const { handleSubmit } = bankForm;

  const { mutate: submitCommand, isPending } = useMutation({
    mutationFn: async (commandData: any) => {
      if (!network) toast.error("Please select a network");
      const data = await postData("/api/v1/mikrotik-command", {
        ...commandData,
        network_id: network,
      });
      return data?.data;
    },
    onSuccess: (data) => {
      console.log(data);
      setCommand(data);
    },
    onError: (error: any) => { },
  });

  const onSubmit = async (data: any) => {
    console.log(data);
    submitCommand(data);
  };

  const onError = async (data: any) => {
    console.log(data);
  };
  const commands = [
    { id: "/ip/address/print", name: "/ip/address/print" },
    { id: "/ppp/profile/print", name: "/ppp/profile/print" },
    { id: "/ppp/secret/print", name: "/ppp/secret/print" },
    { id: "/ppp/active/print", name: "/ppp/active/print" },
  ];
  return (
    <>
      <FormProvider {...bankForm}>
        <form onSubmit={handleSubmit(onSubmit, onError)}>
          <div className="p-5 flex-none gap-4 md:flex lg:flex xl:flex">
            <div className="flex-1">
              <DropdownList
                name="network"
                idName="network_id"
                getLabel={(network) => network?.name}
                isMulti={false}
                placeholder="Select network"
                onChange={(network) => setNetwork(network?.value)}
              />
            </div>
            <div className="flex-1">
              <DropdownList
                name="client"
                idName="client_id"
                getLabel={(client) => client?.name}
                isMulti={false}
                placeholder="Select client"
                onChange={(network) => setNetwork(network?.value)}
                isDisabled={true}
              />
            </div>
            <div className="flex-1">
              <DropdownList
                name="command"
                idName="command"
                getLabel={(command) => command?.name}
                isMulti={false}
                initialData={commands}
                placeholder="Select command"
                isEnabled={false}
                onChange={(command: any) =>
                  submitCommand({ command: command?.value })
                }
              />
            </div>
          </div>
          <div className="p-5">
            <div>
              <div className="min-h-screen bg-gray-900 flex items-center justify-center p-6 rounded-md">
                <div className="space-y-6 max-w-3xl w-full">
                  <div className="bg-gray-800 text-gray-100 font-mono p-4 rounded-lg border border-gray-700 relative">
                    {isPending && (
                      <div className="text-center absolute inset-0 flex justify-center mt-5">
                        <Spinner
                          size="sm"
                          aria-label="Center-aligned spinner example"
                        />
                      </div>
                    )}
                    {command && (
                      <>
                        <h3 className="text-green-400 mb-2">Result:</h3>
                        <pre>{JSON.stringify(command, null, 2)}</pre>
                      </>
                    )}
                  </div>
                </div>
              </div>
            </div>
          </div>
          <input className="opacity-0" type="submit" ref={inputRef} />
        </form>
      </FormProvider>
    </>
  );
};

export default CommandList;
