import Button from "@/UI/Button";
import { addReturnPurchase } from "@/redux/rtk/features/PurchaseReturnList/PurchaseReturnListSlice";
import { Card, DatePicker, Form, Input } from "antd";
import dayjs from "dayjs";
import moment from "moment";
import { Fragment, useCallback, useEffect, useState } from "react";
import { useDispatch, useSelector } from "react-redux";
import { useNavigate, useParams } from "react-router-dom";
import { loadSinglePurchase } from "../../redux/rtk/features/purchase/purchaseSlice";
import PurchaseProductListCard from "../Card/purchaseInvoice/PurchaseProductListCard";
import Loader from "../Loader/Loader";
import Payments from "./Payments";

const AddReturnPurchase = () => {
  const { id } = useParams();
  let navigate = useNavigate();
  const [formData, setFormData] = useState({});

  const [loading, setLoading] = useState(false);
  const [totalReturnAmount, setTotalReturnAmount] = useState(0);
  // make a button click fucnciton to set loading to true

  //dispatch
  const dispatch = useDispatch();
  const purchase = useSelector((state) => state.purchases.purchase);

  const { singlePurchaseInvoice, returnPurchaseInvoice } = purchase
    ? purchase
    : {};
  const [list, setList] = useState([]);
  const [date, setDate] = useState(moment());

  const [form] = Form.useForm();
  const nameValue = Form.useWatch("name", form);

  useEffect(() => {
    dispatch(loadSinglePurchase(id));
  }, [id]);

  useEffect(() => {
    if (singlePurchaseInvoice) {
      const list = singlePurchaseInvoice.purchaseInvoiceProduct?.map((item) => {
        const returnItem = returnPurchaseInvoice?.map((rItem) =>
          rItem.returnPurchaseInvoiceProduct?.find(
            (pItem) => pItem?.productId === item?.productId
          )
        );
        // .reduce(
        //   (acc, item) => {
        //     if (item) {
        //       return {
        //         productQuantity:
        //           acc?.productQuantity +
        //           (item?.productQuantity || 0) +
        //           (item?.damageQuantity || 0),
        //       };
        //     } else {
        //       return acc;
        //     }
        //   },
        //   { productQuantity: 0 }
        // );

        const itemCopy = { ...item };

        if (returnItem) {
          itemCopy.returnQuantity = 0;
          itemCopy.productQuantity =
            itemCopy.productQuantity - returnItem?.productQuantity;
          itemCopy.damageQuantity = 0;
        } else {
          itemCopy.returnQuantity = 0;
          itemCopy.damageQuantity = 0;
          itemCopy.remainQuantity = item?.productQuantity;
        }
        return itemCopy;
      });
      setList(list);
    }
  }, [returnPurchaseInvoice, singlePurchaseInvoice]);

  const submitHandler = async ({ note, paidAmount }) => {
    setLoading(true);
    const values = {
      purchaseInvoiceId: id,
      note,
      date: moment(date._d).format(),
      instantReturnAmount: paidAmount || [],
      returnPurchaseInvoiceProduct: Object.entries(formData).map(
        ([id, { value, damageQuantity }]) => {
          return {
            purchaseInvoiceProductId: parseInt(id),
            productQuantity: value || 0,
            damageQuantity: damageQuantity || 0,
          };
        }
      ),
    };
    const filteredValues = values.returnPurchaseInvoiceProduct.filter(
      (item) => item.productQuantity !== null && item.productQuantity !== null
    );
    const newValues = {
      ...values,
      returnPurchaseInvoiceProduct: filteredValues,
    };
    const resp = await addReturnPurchase(newValues);
    if (resp.message === "success") {
      navigate(-1);
    }
    setLoading(false);
  };

  const updateHandler = useCallback(
    ({ id, value }) => {
      const item = list.find((item) => item.id === id);
      if (item) {
        formData[id] = { value };
        item.returnQuantity = value;
        item.remainQuantity = item.productQuantity - value;
        setList([...list]);
        setFormData({ ...formData });
      }
    },

    [list]
  );

  const updateDamage = useCallback(
    ({ id, value }) => {
      const item = list.find((item) => item.id === id);
      if (item) {
        formData[id] = { ...formData[id], damageQuantity: value };
        item.damageQuantity = value;
        setList([...list]);
        setFormData({ ...formData });
      }
    },

    [formData, list]
  );

  const totalReturnQuantity = () => {
    return list.reduce((acc, item) => {
      const returnAmount = item.returnQuantity * item.productUnitPurchasePrice;
      const returnDamageQuantity =
        item?.damageQuantity * item.productUnitPurchasePrice;
      return acc + (returnAmount + returnDamageQuantity || 0);
    }, 0);
  };

  // set total return amount to state from totalReturnQuantity
  useEffect(() => {
    setTotalReturnAmount(totalReturnQuantity());
  }, [list]);

  return (
    <div>
      <div className="mr-top">
        {singlePurchaseInvoice ? (
          <Fragment key={singlePurchaseInvoice.id}>
            <Card bordered={false} className="criclebox h-full m-3">
              <div className="flex justify-between">
                <h5 className="text-xl">
                  <span className="mr-left">
                    Invoice : {singlePurchaseInvoice.id}
                  </span>
                </h5>
              </div>
              <div className="">
                <PurchaseProductListCard
                  formData={formData}
                  updateReturn={true}
                  returnOnChange={updateHandler}
                  list={list}
                  updateDamage={updateDamage}
                />
                <div className="flex justify-between card-body my-4">
                  <div className="mb-auto">
                    <p
                      className="mr-left hidden"
                      style={{
                        backgroundColor: "#FDCCCC",
                        padding: "10px",
                        paddingRight: "20px",
                        borderRadius: "2px",
                      }}>
                      Total Return Amount :
                      <strong>
                        {"  "}
                        {totalReturnAmount ? totalReturnAmount : 0}
                      </strong>
                    </p>
                  </div>
                  <div className="mr-right min-w-[400px]">
                    <Form
                      labelAlign="right"
                      labelCol={{
                        span: 4,
                      }}
                      initialValues={{
                        date: dayjs(new Date()),
                      }}
                      wrapperCol={{
                        span: 26,
                      }}
                      form={form}
                      onFinish={submitHandler}
                      autoComplete="off">
                      <div className="flex justify-between mb-2">
                        <span className="">Date: </span>
                        <div className="w-[65%]">
                          <Form.Item name="date" className="mb-0">
                            <DatePicker
                              onChange={(date) => setDate(date._d)}
                              style={{ width: "100%" }}
                            />
                          </Form.Item>
                        </div>
                      </div>
                      <div className="flex justify-between mb-2">
                        <span className="">Note: </span>
                        <div className="w-[65%]">
                          <Form.Item name="note" className="mb-0">
                            <Input.TextArea placeholder="Note" />
                          </Form.Item>
                        </div>
                      </div>

                      <div className="mt-3 flex justify-between">
                        <p className="mr-left">Total Return Amount: </p>
                        <p className="font-extrabold">
                          {totalReturnAmount || 0}
                        </p>
                      </div>

                      <div className="flex justify-between mt-2 mb-2">
                        <span className="">Paid Amount: </span>
                        <div className="w-[65%] flex items-center justify-between gap-2">
                          <Payments />
                        </div>
                      </div>

                      <Form.Item style={{ marginTop: "20px" }} className="mb-2">
                        <Button
                          className="bg-red-500 hover:bg-red-600 text-white"
                          type="submit"
                          block
                          loading={loading}>
                          Make Return
                        </Button>
                      </Form.Item>
                    </Form>
                  </div>
                </div>
              </div>
            </Card>
          </Fragment>
        ) : (
          <Loader />
        )}
      </div>
    </div>
  );
};

export default AddReturnPurchase;
