import { useFormikContext } from "formik";

import FormGroup from "../components/FormGroup";
import { toast } from "sonner";

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

const SystemFileUpload = ({ name, selectedFile }: SystemFileUploadProps) => {
  const { setFieldValue } = useFormikContext();
  const handleFileUploadClick = () => console.log(selectedFile);
  return (
    <div className="py-8 w-full">
      <FormGroup>
        <div className="flex-1 flex justify-end md:w-2/3">
          <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;
