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="mt-4 w-full flex flex-col items-center justify-center rounded-2xl border border-slate-800 bg-slate-900/40 p-10 text-center file:px-3 file:border file:border-gray-500 file:rounded-lg file:bg-blue-800 file:mr-5"
            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-1/4 text-white bg-green-700 hover:bg-green-800 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;
