import { Grid, TextField, Button } from "@mui/material";
import { useEffect, useState } from "react";
import { freeBuyingPayment } from "../../../province/services/free-buying-payment";
import { useDispatch } from "react-redux";
import { formatJustDate } from "../../../../utils/formatTime";
import ShowImage from "../../../../components/show-image/ShowImage";
import { AddCommentInSettlemetProvince } from "../../services/AddCommentInSettlemetProvince";

function SupporterSettlementModal({ modal_key }) {
  const dispatch = useDispatch();
  const [paymentData, setPaymentData] = useState([]);
  const [comments, setComments] = useState({});
  const [submitting, setSubmitting] = useState({});

  useEffect(() => {
    if (modal_key) {
      dispatch(
        freeBuyingPayment({ province_kill_request_key: modal_key })
      ).then((action) => {
        const response = action.payload?.data;
        if (response && Array.isArray(response)) {
          const formattedPayments = response.map((payment) => ({
            ...payment,
            date: formatJustDate(payment.date),
          }));

          setPaymentData(formattedPayments);

          const initialComments = {};
          formattedPayments.forEach((payment) => {
            initialComments[payment.key] =
              payment.paymentDeadlineSupporterMessage || "";
          });

          setComments(initialComments);
        }
      });
    }
  }, [dispatch, modal_key]);

  const handleCommentChange = (paymentKey, value) => {
    setComments((prev) => ({
      ...prev,
      [paymentKey]: value,
    }));
  };

  const handleSubmitComment = (paymentKey) => {
    const comment = comments[paymentKey]?.trim() || "";

    setSubmitting((prev) => ({ ...prev, [paymentKey]: true }));

    const data = {
      key: paymentKey,
      payment_deadline_supporter_message: comment,
    };

    dispatch(AddCommentInSettlemetProvince(data))
      .then((action) => {
        if (action.payload?.status === 200) {
          if (modal_key) {
            return dispatch(
              freeBuyingPayment({ province_kill_request_key: modal_key })
            ).then((action) => {
              const response = action.payload?.data;
              if (response && Array.isArray(response)) {
                const formattedPayments = response.map((payment) => ({
                  ...payment,
                  date: formatJustDate(payment.date),
                }));
                setPaymentData(formattedPayments);
              }
            });
          }
        }
      })
      .finally(() =>
        setSubmitting((prev) => ({ ...prev, [paymentKey]: false }))
      );
  };

  return (
    <Grid
      sx={{
        overflowY: "auto",
        display: "flex",
        flexDirection: "row",
        justifyContent: "center",
        flexWrap: "wrap",
        gap: "16px",
        alignItems: "center",
        padding: "20px",
      }}
    >
      {paymentData.map((payment) => (
        <Grid
          key={payment.key}
          sx={{
            display: "flex",
            alignItems: "center",
            justifyContent: "center",
            border: "1px solid #888888",
            borderRadius: "20px",
            padding: "20px",
            marginTop: "20px",
            minWidth: "300px",
          }}
        >
          <Grid
            mt={2}
            sx={{
              display: "flex",
              flexDirection: "column",
              alignItems: "center",
            }}
          >
            {payment.image && (
              <Grid item sx={{ width: "50px", mb: 2 }}>
                <ShowImage src={payment.image} />
              </Grid>
            )}

            <Grid item sx={{ mx: 1, width: "100%" }}>
              <TextField
                size="small"
                fullWidth
                variant="outlined"
                label="مبلغ"
                value={payment.amount?.toLocaleString() || ""}
                InputProps={{
                  readOnly: true,
                }}
              />
            </Grid>

            {payment.date && (
              <Grid mt={2} item sx={{ mx: 1, width: "100%" }}>
                <TextField
                  size="small"
                  fullWidth
                  variant="outlined"
                  label="تاریخ پرداخت"
                  value={payment.date}
                  InputProps={{
                    readOnly: true,
                    style: { fontSize: 14 },
                  }}
                />
              </Grid>
            )}

            <Grid mt={2} item sx={{ mx: 1, width: "100%" }}>
              <TextField
                size="small"
                fullWidth
                variant="outlined"
                label="دیدگاه"
                multiline
                rows={4}
                value={comments[payment.key] || ""}
                onChange={(e) =>
                  handleCommentChange(payment.key, e.target.value)
                }
                InputProps={{
                  style: { fontSize: 14 },
                }}
                sx={{
                  "& .MuiInputBase-root": {
                    height: "auto",
                    alignItems: "flex-start",
                  },
                }}
              />
            </Grid>

            <Grid mt={2} item sx={{ mx: 1, width: "100%" }}>
              <Button
                fullWidth
                variant="contained"
                onClick={() => handleSubmitComment(payment.key)}
                disabled={submitting[payment.key]}
              >
                ثبت
              </Button>
            </Grid>
          </Grid>
        </Grid>
      ))}
    </Grid>
  );
}

export default SupporterSettlementModal;
