import Button from "@/UI/Button";
import { addReturnSale } from "@/redux/rtk/features/SaleReturnList/SaleReturnListSlice";
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 { loadSingleSale } from "../../redux/rtk/features/sale/saleSlice";
import SaleProductListCard from "../Card/saleInvoice/SaleProductListCard";
import Loader from "../Loader/Loader";
import Payments from "./Payments";

const AddReturnSale = () => {
  const { id } = useParams();
  let navigate = useNavigate();
  const [formData, setFormData] = useState({});
  const [totalReturnAmount, setTotalReturnAmount] = useState(0);

  const [loading, setLoading] = useState(false);

  //dispatch
  const dispatch = useDispatch();
  const sale = useSelector((state) => state.sales.sale);
  const { singleSaleInvoice, returnSaleInvoice } = sale ? sale : {};
  const [list, setList] = useState([]);
  const [date, setDate] = useState(moment());

  const [form] = Form.useForm();

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

  useEffect(() => {
    if (singleSaleInvoice) {
      const list = singleSaleInvoice.saleInvoiceProduct.map((item) => {
        const returnItem = returnSaleInvoice
          ?.map((rItem) =>
            rItem.returnSaleInvoiceProduct.find(
              (pItem) => pItem.productId === item.productId
            )
          )
          .reduce(
            (acc, item) => {
              if (item) {
                return {
                  productQuantity:
                    acc.productQuantity +
                    item.productQuantity +
                    item.damageQuantity,
                };
              } else {
                return acc;
              }
            },
            { productQuantity: 0 }
          );
        const itemCopy = { ...item };

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

  const submitHandler = async ({ note, paidAmount }) => {
    setLoading(true);
    const values = {
      saleInvoiceId: id,
      note,
      instantReturnAmount: paidAmount || [],
      date: moment(date._d).format(),

      returnSaleInvoiceProduct: Object.entries(formData).map(
        ([id, { value, damageQuantity }]) => {
          return {
            saleInvoiceProductId: parseInt(id),
            productQuantity: value || 0,
            damageQuantity: damageQuantity || 0,
          };
        }
      ),
    };
    const filteredValues = values.returnSaleInvoiceProduct.filter(
      (item) => item.productQuantity !== null && item.productQuantity !== null
    );
    const newValues = { ...values, returnSaleInvoiceProduct: filteredValues };
    const resp = await addReturnSale(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] = { ...formData[id], value };
        item.returnQuantity = value;
        setList([...list]);
        setFormData({ ...formData });
      }
    },

    [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 = useCallback(() => {
    return list.reduce((acc, item) => {
      return (
        acc +
        (item.returnQuantity + item?.damageQuantity) * item.productUnitSalePrice
      );
    }, 0);
  }, [list]);

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

  return (
    <div className="w-full">
      <div className="mr-top w-full">
        {singleSaleInvoice ? (
          <Fragment key={singleSaleInvoice.id}>
            <Card bordered={false} className="criclebox h-full m-2 sm:m-3">
              <div className="flex flex-col sm:flex-row justify-between gap-2">
                <h5 className="text-lg sm:text-xl">
                  <span className="mr-left">
                    Invoice : {singleSaleInvoice.id}
                  </span>
                </h5>
              </div>
              <div className="w-full overflow-x-auto">
                <SaleProductListCard
                  formData={formData}
                  updateReturn={true}
                  returnOnChange={updateHandler}
                  updateDamage={updateDamage}
                  list={list}
                />
                <div className="flex flex-col lg:flex-row justify-between gap-4 card-body my-4">
                  <div className="mb-auto w-full lg:w-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="w-full lg:max-w-[400px] lg:min-w-[400px] md:max-w-[500px]">
                    <Form
                      labelAlign="right"
                      initialValues={{
                        date: dayjs(),
                      }}
                      form={form}
                      onFinish={submitHandler}
                      autoComplete="off">
                      <div className="flex flex-col sm:flex-row justify-between mb-2 gap-2">
                        <span className="sm:min-w-[100px]">Date: </span>
                        <div className="w-full sm: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 flex-col sm:flex-row justify-between mb-2 gap-2">
                        <span className="sm:min-w-[100px]">Note: </span>
                        <div className="w-full sm:w-[65%]">
                          <Form.Item name="note" className="mb-0">
                            <Input.TextArea placeholder="Note" rows={3} />
                          </Form.Item>
                        </div>
                      </div>

                      <div className="mt-3 flex flex-col sm:flex-row justify-between gap-2 p-2 bg-gray-50 rounded">
                        <p className="mr-left font-medium">Total Return Amount: </p>
                        <p className="font-extrabold text-lg">
                          {totalReturnAmount || 0}
                        </p>
                      </div>

                      <div className="flex flex-col sm:flex-row justify-between mb-2 gap-2 mt-3">
                        <span className="sm:min-w-[100px]">Paid Amount: </span>
                        <div className="w-full sm:w-[65%] flex items-center justify-between gap-2">
                          <Payments />
                        </div>
                      </div>

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

export default AddReturnSale;
