import React, { useContext, useState } from "react";
import { Grid } from "../../../../components/grid/Grid";
import { Button, TextField } from "@mui/material";
import { useDispatch } from "react-redux";
import { AppContext } from "../../../../contexts/AppContext";
import { guildEditOutOfProvinceService } from "../../../slaughter-house/services/slaughterEditOutOfProvinceService";
import { getRoleFromUrl } from "../../../../utils/getRoleFromUrl";
import { Done } from "@mui/icons-material";

export const StewardOutProvinceRegistrationCodeInput = ({
  item,
  fetchApiData,
}) => {
  const dispatch = useDispatch();
  const [openNotif] = useContext(AppContext);
  const [registrationCode, setRegistrationCode] = useState(
    item?.loggedRegistrationCode || ""
  );

  const handleSubmit = () => {
    dispatch(
      guildEditOutOfProvinceService({
        key: item?.key,
        register_code: parseInt(registrationCode),
        role: getRoleFromUrl(),
        // Include all required fields from item
        date: item?.date,
        buyer_name: item?.buyerName,
        buyer_mobile: item?.buyerMobile,
        province: item?.province,
        city: item?.city,
        clearance_code: item?.clearanceCode,
        number_of_carcasses: item?.numberOfCarcasses,
        quarantine_weight_of_carcasses: item?.quarantineWeightOfCarcasses,
        weight_of_carcasses: item?.weightOfCarcasses,
        ...(item?.buyer?.key && { buyer_key: item?.buyer?.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",
        });
        fetchApiData();
      }
    });
  };

  return (
    <Grid
      container
      direction="row"
      alignItems="center"
      justifyContent="flex-start"
      gap={1}
      sx={{ position: "relative" }}
    >
      <TextField
        value={registrationCode}
        size="small"
        onChange={(e) => setRegistrationCode(e.target.value)}
        style={{ minWidth: "150px" }}
        disabled={item?.loggedRegistrationCode}
        placeholder="کد احراز"
        inputProps={{
          inputMode: "numeric",
          pattern: "[0-9]*",
        }}
        type="number"
      />
      {!item?.loggedRegistrationCode && registrationCode && (
        <Button
          size="small"
          variant="contained"
          color="primary"
          onClick={handleSubmit}
          sx={{
            position: "absolute",
            right: "0",
            minWidth: "40px",
            width: "40px",
            height: "38px",
          }}
        >
          <Done />
        </Button>
      )}
    </Grid>
  );
};
