import React, { useContext, useRef, useState, useEffect } from "react";
import {
  InputAdornment,
  TextField,
  Tooltip,
  CircularProgress,
  Grid,
  Box,
  Button,
  Paper,
  Typography,
  IconButton,
  Collapse,
  useMediaQuery,
  useTheme,
} from "@mui/material";
import { useDispatch } from "react-redux";
import PageviewIcon from "@mui/icons-material/Pageview";
import EditIcon from "@mui/icons-material/Edit";
import DeleteIcon from "@mui/icons-material/Delete";
import { PropTypes } from "prop-types";
import { AppContext } from "../../../../contexts/AppContext";
import { LabelField } from "../../../../components/label-field/LabelField";
import { vetFarmSubmitClearenceCodeService } from "../../services/vet-farm-submit-quarantine-code";
import { vetFarmEditQuarantineCodeService } from "../../services/vet-farm-edit-quarantine-code";
import { vetFarmGetQuarantineCodeService } from "../../services/vet-farm-get-quarantine-code";
import { vetFarmDeleteQuarantineCodeService } from "../../services/vet-farm-delete-quarantine-code";
import { getRoleFromUrl } from "../../../../utils/getRoleFromUrl";
import { CLOSE_MODAL } from "../../../../lib/redux/slices/appSlice";

export const VetFarmSubmitClearanceCode = ({ readOnly, updateTable, item }) => {
  const dispatch = useDispatch();
  const [openNotif] = useContext(AppContext);
  const theme = useTheme();
  const isMobile = useMediaQuery(theme.breakpoints.down("md"));
  const [currentSubmittingIndex, setCurrentSubmittingIndex] = useState(null);
  const [codes, setCodes] = useState([]);
  const [isAddNewCodeOpen, setIsAddNewCodeOpen] = useState(false);
  const [newCode, setNewCode] = useState({
    code: "",
    quantity: "",
    trafficCode: "",
    requestCodeKey: "",
  });

  const role = getRoleFromUrl() === "VetFarm" || getRoleFromUrl() === "AdminX";

  const fetchQuarantineCodes = () => {
    dispatch(
      vetFarmGetQuarantineCodeService({
        poultry_request_key: item?.key,
      })
    ).then((r) => {
      if (r.payload?.data) {
        setCodes(
          r.payload.data.map((code) => ({
            ...code,
            requestCodeKey: code.key,
            isEdit: false,
          }))
        );
      }
    });
  };

  useEffect(() => {
    fetchQuarantineCodes();
  }, [dispatch, item?.key]);

  const handleSubmitNewCode = () => {
    dispatch(CLOSE_MODAL());

    if (!newCode.code || !newCode.quantity) {
      openNotif({
        vertical: "top",
        horizontal: "center",
        msg: "لطفا کد و تعداد را وارد کنید",
        severity: "error",
      });
      return;
    }

    dispatch(
      vetFarmSubmitClearenceCodeService({
        quarantine_code: newCode.code.toUpperCase(),
        quarantine_quantity: newCode.quantity,
        traffic_code: newCode.trafficCode || null,
        poultry_request_key: item?.key,
      })
    ).then((r) => {
      if (r.payload.error) {
        openNotif({
          vertical: "top",
          horizontal: "center",
          msg: r.payload.error,
          severity: "error",
        });
      } else {
        openNotif({
          vertical: "top",
          horizontal: "center",
          msg: "کد با موفقیت ثبت شد",
          severity: "success",
        });

        fetchQuarantineCodes();

        setCodes([
          ...codes,
          {
            quarantineCode: newCode.code.toUpperCase(),
            quarantineQuantity: newCode.quantity,
            trafficCode: newCode.trafficCode,
            requestCodeKey: r.payload?.key,
            isEdit: false,
          },
        ]);
        setNewCode({ code: "", quantity: "", trafficCode: "" });

        if (updateTable) updateTable();
      }
    });
  };

  const handleEditCode = (index) => {
    const codeItem = codes[index];

    if (!codeItem.quarantineCode || !codeItem.quarantineQuantity) {
      openNotif({
        vertical: "top",
        horizontal: "center",
        msg: "لطفا کد و تعداد را وارد کنید",
        severity: "error",
      });
      return;
    }

    setCurrentSubmittingIndex(index);

    dispatch(
      vetFarmEditQuarantineCodeService({
        request_code_key: codeItem?.requestCodeKey,
        quarantine_code: codeItem?.quarantineCode.toUpperCase(),
        quarantine_quantity: codeItem?.quarantineQuantity,
        traffic_code: codeItem?.trafficCode || null,
      })
    )
      .then((r) => {
        if (r.payload.error) {
          openNotif({
            vertical: "top",
            horizontal: "center",
            msg: r.payload.error || "خطا در ویرایش کد",
            severity: "error",
          });
        } else {
          openNotif({
            vertical: "top",
            horizontal: "center",
            msg: "کد با موفقیت ویرایش شد",
            severity: "success",
          });

          setCodes((prevCodes) =>
            prevCodes.map((code, i) =>
              i === index ? { ...code, isEdit: false } : code
            )
          );
          fetchQuarantineCodes();

          if (updateTable) updateTable();
        }
      })
      .finally(() => {
        setCurrentSubmittingIndex(null);
      });
  };

  const handleDeleteCode = (index) => {
    const codeItem = codes[index];
    if (!codeItem?.requestCodeKey) return;

    setCurrentSubmittingIndex(index);

    dispatch(
      vetFarmDeleteQuarantineCodeService({
        request_code_key: codeItem?.requestCodeKey,
      })
    )
      .then((r) => {
        if (r.error) {
          openNotif({
            vertical: "top",
            horizontal: "center",
            msg: r.error,
            severity: "error",
          });
        } else {
          openNotif({
            vertical: "top",
            horizontal: "center",
            msg: "کد با موفقیت حذف شد",
            severity: "success",
          });

          setCodes((prevCodes) => prevCodes.filter((_, i) => i !== index));
          fetchQuarantineCodes();

          if (updateTable) updateTable();
        }
      })
      .finally(() => {
        setCurrentSubmittingIndex(null);
      });
  };

  const handleCodeChange = (index, field, value) => {
    setCodes((prevCodes) =>
      prevCodes.map((code, i) =>
        i === index ? { ...code, [field]: value } : code
      )
    );
  };

  const toggleEdit = (index) => {
    setCodes((prevCodes) =>
      prevCodes.map((code, i) =>
        i === index ? { ...code, isEdit: !code.isEdit } : code
      )
    );
  };

  const handleNewCodeChange = (field, value) => {
    setNewCode({
      ...newCode,
      [field]: value,
    });
  };

  return (
    <Box
      sx={{
        width: {
          xs: "340px",
          md: "690px",
        },
      }}
    >
      <Grid
        sx={{
          width: "100%",
          maxHeight: "400px",
          overflowY: "auto",
        }}
      >
        {codes.length > 0 && (
          <Box sx={{ mb: 3, px: 1 }}>
            <Typography variant="subtitle1" gutterBottom>
              کدهای ثبت شده:
            </Typography>
            {codes.map((codeItem, index) => (
              <Paper
                key={index}
                elevation={2}
                sx={{ p: 2, mb: 2, border: "1px solid #eee", borderRadius: 2 }}
              >
                <Box
                  sx={{
                    display: "flex",
                    alignItems: "center",
                    gap: 2,
                    flexWrap: "wrap",
                    width: "100%",
                  }}
                >
                  <TextField
                    label="کد حمل"
                    size="small"
                    value={codeItem.trafficCode || ""}
                    onChange={(e) =>
                      handleCodeChange(index, "trafficCode", e.target.value)
                    }
                    disabled={!codeItem.isEdit || !role}
                    sx={{ width: { xs: "46%", md: "160px" } }}
                  />
                  <TextField
                    label="کد قرنطینه"
                    size="small"
                    value={codeItem.quarantineCode || ""}
                    onChange={(e) =>
                      handleCodeChange(index, "quarantineCode", e.target.value)
                    }
                    disabled={!codeItem.isEdit || !role}
                    InputProps={{
                      startAdornment: (
                        <InputAdornment position="start">
                          <ViewCodeComponent
                            clearanceCode={codeItem.quarantineCode}
                          />
                        </InputAdornment>
                      ),
                    }}
                    sx={{ width: { xs: "46%", md: "160px" } }}
                  />

                  <TextField
                    label="تعداد"
                    type="number"
                    size="small"
                    value={codeItem.quarantineQuantity || ""}
                    onChange={(e) =>
                      handleCodeChange(
                        index,
                        "quarantineQuantity",
                        e.target.value
                      )
                    }
                    disabled={!codeItem.isEdit || !role}
                    sx={{ width: { xs: "35%", md: "80px" } }}
                  />

                  {codeItem.isEdit ? (
                    <Button
                      variant="contained"
                      color="success"
                      onClick={() => handleEditCode(index)}
                      disabled={currentSubmittingIndex === index || !role}
                      startIcon={
                        currentSubmittingIndex === index ? (
                          <CircularProgress size={20} />
                        ) : null
                      }
                      size="small"
                    >
                      ذخیره
                    </Button>
                  ) : (
                    <Box sx={{ display: "flex", alignItems: "center", gap: 1 }}>
                      {role && (
                        <IconButton
                          color="primary"
                          onClick={() => toggleEdit(index)}
                          disabled={readOnly}
                          size="small"
                        >
                          <EditIcon />
                        </IconButton>
                      )}
                      {role && (
                        <IconButton
                          color="error"
                          onClick={() => handleDeleteCode(index)}
                          disabled={
                            readOnly || currentSubmittingIndex === index
                          }
                          size="small"
                        >
                          <DeleteIcon />
                        </IconButton>
                      )}
                      <Grid
                        xs={12}
                        sx={{
                          width: "80px",
                          borderStyle: "solid",
                          p: 1,
                          borderRadius: "10px",
                          borderWidth: "0px 1px 0px 1px",
                          borderColor: "gray",
                          display: "flex",
                          flexDirection: "column",
                          alignItems: "center",
                          justifyContent: "center",
                        }}
                      >
                        <Typography variant="caption" sx={{ color: "gray" }}>
                          استعلام
                        </Typography>
                        <Typography>
                          {codeItem?.systemQuarantineQuantity}
                        </Typography>
                      </Grid>
                    </Box>
                  )}
                </Box>
              </Paper>
            ))}
          </Box>
        )}
      </Grid>

      {role && !readOnly && (
        <>
          {isMobile ? (
            <>
              <Button
                variant="text"
                size="medium"
                onClick={() => setIsAddNewCodeOpen(!isAddNewCodeOpen)}
                sx={{
                  justifyContent: "flex-start",
                  fontWeight: "bold",
                }}
              >
                {isAddNewCodeOpen ? "- " : "+ "}
                افزودن کد جدید
              </Button>

              <Collapse in={isAddNewCodeOpen}>
                <Paper
                  elevation={2}
                  sx={{ p: 2, border: "1px solid #eee", borderRadius: 2 }}
                >
                  <Grid container spacing={2} alignItems="center" xs={12}>
                    <Grid item xs={12} md={3.5}>
                      <TextField
                        label="کد حمل"
                        size="small"
                        value={newCode.trafficCode}
                        onChange={(e) =>
                          handleNewCodeChange(
                            "trafficCode",
                            e.target.value.toUpperCase()
                          )
                        }
                        fullWidth
                      />
                    </Grid>
                    <Grid item xs={12} md={3.5}>
                      <TextField
                        label="کد قرنطینه"
                        size="small"
                        value={newCode.code}
                        onChange={(e) =>
                          handleNewCodeChange(
                            "code",
                            e.target.value.toUpperCase()
                          )
                        }
                        fullWidth
                      />
                    </Grid>

                    <Grid item xs={12} md={2.5}>
                      <TextField
                        label="تعداد"
                        type="number"
                        size="small"
                        value={newCode.quantity}
                        onChange={(e) =>
                          handleNewCodeChange("quantity", e.target.value)
                        }
                        fullWidth
                      />
                    </Grid>
                    <Grid item xs={12} md={2.5}>
                      <Button
                        variant="contained"
                        color="primary"
                        onClick={handleSubmitNewCode}
                        disabled={!newCode.code || !newCode.quantity}
                        size="small"
                        fullWidth
                      >
                        افزودن
                      </Button>
                    </Grid>
                  </Grid>
                </Paper>
              </Collapse>
            </>
          ) : (
            <Grid container xs={12} pt={2}>
              <LabelField label="افزودن کد جدید">
                <Grid container spacing={2} alignItems="center" xs={12} p={1}>
                  <Grid item xs={12} md={3.5}>
                    <TextField
                      label="کد حمل"
                      size="small"
                      value={newCode.trafficCode}
                      onChange={(e) =>
                        handleNewCodeChange(
                          "trafficCode",
                          e.target.value.toUpperCase()
                        )
                      }
                      fullWidth
                    />
                  </Grid>
                  <Grid item xs={12} md={3.5}>
                    <TextField
                      label="کد قرنطینه"
                      size="small"
                      value={newCode.code}
                      onChange={(e) =>
                        handleNewCodeChange(
                          "code",
                          e.target.value.toUpperCase()
                        )
                      }
                      fullWidth
                    />
                  </Grid>

                  <Grid item xs={12} md={2.5}>
                    <TextField
                      label="تعداد"
                      type="number"
                      size="small"
                      value={newCode.quantity}
                      onChange={(e) =>
                        handleNewCodeChange("quantity", e.target.value)
                      }
                      fullWidth
                    />
                  </Grid>
                  <Grid item xs={12} md={2.5}>
                    <Button
                      variant="contained"
                      color="primary"
                      onClick={handleSubmitNewCode}
                      disabled={!newCode.code || !newCode.quantity}
                      size="small"
                      fullWidth
                    >
                      افزودن
                    </Button>
                  </Grid>
                </Grid>
              </LabelField>
            </Grid>
          )}
        </>
      )}
    </Box>
  );
};

const ViewCodeComponent = ({ clearanceCode }) => {
  const formRef = useRef(null);

  const handleImageClick = () => {
    if (formRef.current) {
      formRef.current.submit();
    }
  };

  return (
    <Tooltip title="مشاهده گواهینامه" arrow>
      <form
        action="https://e.ivo.ir/Rahgiri/Gidprnt.aspx"
        method="post"
        target="_blank"
        ref={formRef}
        style={{ cursor: "pointer" }}
      >
        <input name="gid" type="hidden" value={clearanceCode} />
        <PageviewIcon color="primary" onClick={handleImageClick} />
      </form>
    </Tooltip>
  );
};

VetFarmSubmitClearanceCode.propTypes = {
  item: PropTypes.shape({
    key: PropTypes.string,
    quarantine_code: PropTypes.string,
    quarantine_quantity: PropTypes.string,
    quarantineCodes: PropTypes.array,
  }),
  updateTable: PropTypes.func,
  readOnly: PropTypes.bool,
};

VetFarmSubmitClearanceCode.defaultProps = {
  readOnly: false,
  updateTable: () => {},
};
