import { useFormikContext } from "formik";
import FormGroup from "../components/FormGroup";
import { toast } from "sonner";
import { useSystemConfig } from "../../../hooks/useSystemConfig";

type SystemFileUploadProps = {
  name: string;
  selectedFile: File | null | undefined;
};

const SystemFileUpload = ({ name, selectedFile }: SystemFileUploadProps) => {
  const { setFieldValue } = useFormikContext();
  const { uploadSettings } = useSystemConfig();

  const handleFileUploadClick = () => {
    if (!selectedFile) return;
    const settings = {
      file: selectedFile,
      opts: {
        timeoutMs: 30000,
        fieldName: "upload",
        uploadUrl: "http://192.168.75.11/upload/software-update/2",
      },
    };
    uploadSettings(settings);
  };

  return (
    <div className="py-8 w-full">
      <div className="border-b border-gray-600">
        <h2>Software Update file upload</h2>
      </div>
      <FormGroup>
        <div className="flex-1 flex md:w-2/3 my-5">
          <input
            type="file"
            name="softwareUpdate"
            id="softwareUpdate"
            className="file:px-10 file:border file:border-gray-500 file:rounded-lg file:bg-blue-800 file:mr-5 w-full max-w-xs"
            onChange={(event) => {
              const file = event.currentTarget.files?.[0];
              if (!file) {
                toast.error("No File selected");
                return;
              }

              if (file?.size > 8 * 1024 * 1024)
                toast.error("File is too large (max 8MB).");
              setFieldValue(name, file);
            }}
          />
        </div>
      </FormGroup>
      <button
        type="button"
        className="w-full max-w-md text-white bg-[#26B170]  hover:bg-green-700 font-small rounded-lg text-sm px-2 py-2.5 disabled:opacity-50 disabled:cursor-not-allowed"
        disabled={!selectedFile}
        onClick={handleFileUploadClick}
      >
        Upload Software Update
      </button>
    </div>
  );
};

export default SystemFileUpload;
