import { Form, Formik } from "formik";
import type { HotlistUploadType } from "../../../types/types";
import { useSystemConfig } from "../../../hooks/useSystemConfig";
import { CAM_BASE } from "../../../utils/config";

const NPEDHotlist = () => {
  const { uploadSettings } = useSystemConfig();
  const initialValue = {
    file: null,
  };

  const handleSubmit = (values: HotlistUploadType) => {
    const settings = {
      file: values.file,
      opts: {
        timeoutMs: 30000,
        fieldName: "upload",
        uploadUrl: `${CAM_BASE}/upload/hotlist-upload/2`,
      },
    };

    uploadSettings(settings);
  };

  return (
    <Formik initialValues={initialValue} onSubmit={handleSubmit}>
      {({ setFieldValue, setErrors, errors }) => {
        return (
          <Form className="flex flex-col space-y-2 px-2">
            <input
              type="file"
              name="file"
              id="file"
              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={(e) => {
                if (e.target.files) {
                  if (e.target.files[0].type !== "text/csv") {
                    setErrors({
                      file: "This file is not a CSV, please select a different one",
                    });
                  }
                  setFieldValue("file", e.target.files[0]);
                } else {
                  setErrors({ file: "no file" });
                }
              }}
            />
            <button
              type="submit"
              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={errors ? true : false}
            >
              Upload
            </button>
            <p>{errors.file && errors.file}</p>
          </Form>
        );
      }}
    </Formik>
  );
};

export default NPEDHotlist;
