import React, { useContext, useEffect, useState } from "react";
import { Grid } from "../../../../components/grid/Grid";
import {
  Button,
  FormControlLabel,
  Switch,
  TextField,
  Typography,
} from "@mui/material";
import { useFormik } from "formik";
import { Yup } from "../../../../lib/yup/yup";
import { useDispatch } from "react-redux";
import { archiveHatchingService } from "../../services/archive-hatching";
import { AppContext } from "../../../../contexts/AppContext";
import { CLOSE_MODAL } from "../../../../lib/redux/slices/appSlice";
import { FileUploader } from "../../../../components/file-uploader/FileUploader";

export const CitySubmitHatchingReport = ({ item, updateTable, isArchive }) => {
  const [checked, setChecked] = useState(item?.violation);
  const [sendToArchive, setSendToArchive] = useState(false);
  const dispatch = useDispatch();
  const handleChange = (event) => {
    setChecked(event.target.checked);
  };
  const handleChangeArchive = (event) => {
    setSendToArchive(event.target.checked);
  };

  const [openNotif] = useContext(AppContext);

  const [filesList, setFilesList] = useState([]);

  const hanleFilesChange = (e) => {
    setFilesList(e);
  };

  const formik = useFormik({
    initialValues: {
      reportText: item?.violationReport,
      bar_image: "",
    },
    validationSchema: Yup.object({
      reportText: Yup.string()
        .required("این فیلد اجباری است!")
        .typeError("لطفا گزارش خود را بیان کنید."),
      bar_image: Yup.array(),
    }),
  });

  useEffect(() => {
    formik.validateForm();
  }, []);

  // const factorPaymentHandler = (imageList, addUpdateIndex) => {
  //   if (imageList[0]) {
  //     formik.setFieldValue(
  //       "bar_image",
  //       imageList.map((img) => fixBase64(img.data_url))
  //     );
  //   }
  //   setProfileImages(imageList);
  // };

  return (
    <Grid container xs={12} justifyContent="center" alignItems="center" gap={2}>
      <FormControlLabel
        control={
          <Switch checked={checked} onChange={handleChange} color="primary" />
        }
        label={checked ? "متخلف" : "بدون تخلف"}
        style={{
          justifyContent: "center",
          alignItems: "center",
          display: "flex",
        }}
      />
      {!isArchive && (
        <FormControlLabel
          control={
            <Switch
              checked={sendToArchive}
              onChange={handleChangeArchive}
              color="primary"
            />
          }
          label={"انتقال به بایگانی"}
          style={{
            justifyContent: "center",
            alignItems: "center",
            display: "flex",
          }}
        />
      )}
      <TextField
        multiline
        rows={4}
        fullWidth
        id="reportText"
        label="متن گزارش"
        variant="outlined"
        value={formik.values.reportText}
        error={
          formik.touched.reportText ? Boolean(formik.errors.reportText) : null
        }
        onChange={formik.handleChange}
        onBlur={formik.handleBlur}
        helperText={
          formik.touched.reportText && Boolean(formik.errors.reportText)
            ? formik.errors.reportText
            : null
        }
      />
      <Typography color="error">
        در صورت آپلود فایل جدید، سندهای پیشین حذف میشوند!
      </Typography>

      {/* <ImageUpload
        onChange={factorPaymentHandler}
        images={profileImages}
        maxNumber={5}
        title={"بارگذاری سند"}
      /> */}

      <FileUploader onChange={hanleFilesChange} />
      {/* {item?.violationImage?.length && !profileImages?.length && (
        <>
          {item?.violationImage?.map((option, i) => (
            <img
              key={i}
              src={option}
              alt="تصویر گزارش"
              style={{ width: "100px", borderRadius: "5px" }}
            />
          ))}
        </>
      )} */}

      <Button
        mt={2}
        disabled={!formik.isValid || formik.isSubmitting}
        fullWidth
        variant="contained"
        onClick={async () => {
          try {
            const req = {
              key: item?.key,
              violation_check: true,
              violation: checked,
              violation_report: formik.values.reportText,
              archive: sendToArchive,
            };

            const formData = new FormData();
            Object.entries(req).forEach(([key, value]) => {
              formData.append(key, value);
            });

            filesList.forEach((file, index) => {
              formData.append(`violation_image_${index}`, file);
            });

            const response = await dispatch(
              archiveHatchingService(filesList.length ? formData : req)
            );

            if (response.error) {
              throw new Error(response.error);
            }

            updateTable(1);
            dispatch(CLOSE_MODAL());
            openNotif({
              vertical: "top",
              horizontal: "center",
              msg: "عملیات با موفقیت انجام شد.",
              severity: "success",
            });
          } catch (error) {
            openNotif({
              vertical: "top",
              horizontal: "center",
              msg: error.message || "خطا در ارسال اطلاعات",
              severity: "error",
            });
          }
        }}
      >
        {formik.isSubmitting ? "در حال ثبت..." : "ثبت"}
      </Button>
    </Grid>
  );
};
