import { Button, DatePicker, Form, Input, Select } from "antd";

import { useEffect, useState } from "react";
import { useDispatch, useSelector } from "react-redux";
import { loadProduct } from "../../redux/rtk/features/product/productSlice";
import { loadSuppliers } from "../../redux/rtk/features/supplier/supplierSlice";
import Products from "./Products";

import { loadAllStoreByUser } from "@/redux/rtk/features/store/storeSlice";
import dayjs from "dayjs";
import { useNavigate } from "react-router-dom";
import { addPurchase } from "../../redux/rtk/features/purchase/purchaseSlice";
import BigDrawer from "../Drawer/BigDrawer";
import AddSup from "../Suppliers/AddSupplier";
import Payments from "./Payments";
import AddStore from "../Store/AddStore";

const AddPurchase = () => {
  const { Option } = Select;
  const [loader, setLoader] = useState(false);
  const [subTotal, setSubTotal] = useState([]);
  const [due, setDue] = useState(0);
  const [selectedSupplier, setSelectedSupplier] = useState();

  const navigate = useNavigate();
  const dispatch = useDispatch();

  useEffect(() => {
    dispatch(loadSuppliers({ status: true, page: 1, count: 10 }));
    dispatch(loadProduct({ query: "all" }));
    dispatch(loadAllStoreByUser());
  }, [dispatch]);

  const allSuppliers = useSelector((state) => state.suppliers.list);
  const { list: productList, loading: productLoading } = useSelector(
    (state) => state.products
  );
  const {
    list: store,
    loading: storeLoading,
    defaultStore,
  } = useSelector((state) => state.store);

  // Form Function
  const [form] = Form.useForm();

  const onFormSubmit = async (values) => {
    try {
      const mergedObject = values.purchaseInvoiceProduct.reduce(
        (accumulator, currentObject) => {
          const productId = currentObject.productId;
          if (!accumulator[productId]) {
            accumulator[productId] = { ...currentObject };
          } else {
            accumulator[productId].productQuantity +=
              currentObject.productQuantity;
          }
          return accumulator;
        },
        {}
      );

      const mergedArray = Object.values(mergedObject);
      const newArray = mergedArray.map((product) => {
        return {
          ...product,
          productId: product.productId,
          productQuantity: product.productQuantity,
          productUnitPurchasePrice: product.productPurchasePrice,
          productUnitSalePrice: product.productSalePrice,
          tax: product.tax,
        };
      });

      const data = {
        ...values,
        purchaseInvoiceProduct: newArray,
        paidAmount: values.paidAmount || [],
      };
      const resp = await dispatch(addPurchase(data));
      if (resp.payload.message === "success") {
        form.resetFields();
        setLoader(false);
        navigate(`/admin/purchase/${resp.payload.data.id}`);
      } else {
        setLoader(false);
      }
    } catch (error) {
      setLoader(false);
    }
  };

  // total calculate
  const totalCalculator = () => {
    const productArray = form.getFieldValue("purchaseInvoiceProduct");

    const subTotal =
      productArray?.reduce((subTotal, current) => {
        const quantity = current?.productQuantity || 0;
        const price = current?.productPurchasePrice || 0;
        const vat = current?.tax || 0;
        const subPrice = price * quantity;
        const totalVat = (vat / 100) * subPrice;
        return [...subTotal, { subPrice, totalVat }];
      }, []) || [];

    setSubTotal(subTotal);

    const total = subTotal?.reduce((acc, item) => acc + item.subPrice, 0);
    const totalTaxAmount = subTotal?.reduce(
      (acc, item) => acc + item.totalVat,
      0
    );
    const totalPayable = total + totalTaxAmount;
    const paidAmountArray = form.getFieldValue("paidAmount") || [];
    const paidAmount = paidAmountArray?.reduce((acc, item) => {
      return acc + (item.amount ? parseInt(item.amount) : 0);
    }, 0);
    const due = totalPayable - paidAmount;
    setDue(due);
  };

  const supplier = allSuppliers?.find((item) => item.id === selectedSupplier);
  const total = subTotal?.reduce((acc, item) => acc + item.subPrice, 0);
  const totalTaxAmount = subTotal?.reduce(
    (acc, item) => acc + item.totalVat,
    0
  );
  const totalPayable = total + totalTaxAmount;
  useEffect(() => {
    if (defaultStore) {
      form.setFieldValue("storeId", defaultStore.id);
    }
  }, [defaultStore, form]);
  return (
    <Form
      form={form}
      className="w-full max-w-full overflow-x-hidden"
      name="dynamic_form_nest_item"
      onFinish={onFormSubmit}
      onFinishFailed={() => {
        setLoader(false);
      }}
      layout="vertical"
      size="large"
      onKeyDown={(e) => {
        if (e.key === "Enter") {
          e.preventDefault();
        }
      }}
      initialValues={{
        paidAmount: 0,
        discount: 0,
        date: dayjs(),
        purchaseInvoiceProduct: [{}],
      }}>
      <div className="flex flex-col lg:flex-row gap-2 sm:gap-4 2xl:h-[calc(100vh-100px)] min-h-[500px] max-w-full overflow-x-hidden">
        <div className="w-full lg:w-[70%] 2xl:w-[75%] max-w-full overflow-x-hidden">
          <Products
            totalCalculator={totalCalculator}
            subTotal={subTotal}
            form={form}
            productList={productList}
            productLoading={productLoading}
          />
        </div>
        <div className="flex flex-col w-full lg:w-[30%] 2xl:w-[25%] max-w-full">
          <div className="flex-grow max-w-full">
            <div className="w-full max-w-full">
              <Form.Item
                label={
                  <>
                    Supplier{" "}
                    <BigDrawer className="" title="Add New Supplier">
                      <AddSup drawer={true} />
                    </BigDrawer>
                  </>
                }
                name="supplierId"
                className="w-full max-w-full mb-2 sm:mb-3"
                rules={[
                  {
                    required: true,
                    message: "Please Select a supplier!",
                  },
                ]}>
                <Select
                  className="w-full max-w-full"
                  loading={!allSuppliers}
                  onChange={(id) => setSelectedSupplier(id)}
                  showSearch
                  placeholder="Select a supplier "
                  optionFilterProp="children"
                  filterOption={(input, option) =>
                    option.children.toLowerCase().includes(input.toLowerCase())
                  }>
                  {allSuppliers &&
                    allSuppliers.map((sup) => (
                      <Option key={sup.id} value={sup.id}>
                        {sup.name}
                      </Option>
                    ))}
                </Select>
              </Form.Item>
              {supplier && (
                <div className="flex flex-col sm:flex-row sm:justify-between gap-2 py-1 px-2 sm:px-4 text-xs sm:text-sm max-w-full overflow-x-hidden">
                  <span className="flex gap-1 min-w-0">
                    <span className="font-medium whitespace-nowrap">Address:</span>
                    <span className="break-words overflow-hidden">{supplier?.address}</span>
                  </span>
                  <span className="flex gap-1 min-w-0">
                    <span className="font-medium whitespace-nowrap">Phone:</span>
                    <span className="break-all">{supplier?.phone}</span>
                  </span>
                </div>
              )}
            </div>
            <Form.Item
              label={
                <>
                  Store{" "}
                  <BigDrawer className="" title="Add New Store">
                    <AddStore drawer={true} />
                  </BigDrawer>
                </>
              }
              name="storeId"
              className="w-full max-w-full mb-2 sm:mb-3"
              rules={[
                {
                  required: true,
                  message: "Please Select a store!",
                },
              ]}>
              <Select
                className="w-full max-w-full"
                loading={storeLoading}
                showSearch
                placeholder="Select a store"
                optionFilterProp="children">
                {store?.map((store) => (
                  <Option key={store.id} value={store.id}>
                    {store.name}
                  </Option>
                ))}
              </Select>
            </Form.Item>

            <Form.Item
              name="date"
              label="Date"
              className="w-full max-w-full mb-2 sm:mb-3"
              layout="horizental"
              required
              rules={[
                {
                  required: true,
                  message: "Please input Date!",
                },
              ]}>
              <DatePicker
                size="small"
                format={"YYYY-MM-DD"}
                className="date-picker w-full max-w-full"
              />
            </Form.Item>

            <Form.Item
              className="w-full max-w-full mb-2 sm:mb-3"
              name="supplierMemoNo"
              label="Supplier Memo">
              <Input className="w-full max-w-full" placeholder="Memo no " />
            </Form.Item>

            <Form.Item className="w-full max-w-full mb-2 sm:mb-3" name="note" label="Note">
              <Input className="w-full max-w-full" placeholder="Note" />
            </Form.Item>
          </div>
          <div className="py-2 px-2 sm:px-0 max-w-full overflow-x-hidden">
            <div className="flex justify-between text-xs sm:text-sm lg:text-base py-1 max-w-full">
              <strong className="whitespace-nowrap">Total amount:</strong>
              <strong className="break-all text-right">{total.toFixed(2)}</strong>
            </div>

            <div className="py-1 flex justify-between items-center text-xs sm:text-sm lg:text-base max-w-full">
              <span className="whitespace-nowrap">Total tax amount:</span>
              <span className="break-all text-right">{totalTaxAmount.toFixed(2)}</span>
            </div>
            <div className="py-1 flex justify-between items-center text-xs sm:text-sm lg:text-base max-w-full">
              <strong className="whitespace-nowrap">Total Payable:</strong>
              <strong className="break-all text-right">{totalPayable.toFixed(2)}</strong>
            </div>

            <div className="py-1 mb-3 sm:mb-4 flex justify-between text-xs sm:text-sm lg:text-base max-w-full">
              <strong className="whitespace-nowrap">Due Amount:</strong>
              <strong className="break-all text-right">{due.toFixed(2)}</strong>
            </div>
            <div className="flex flex-col sm:flex-row sm:justify-between mb-2 gap-2 text-xs sm:text-sm lg:text-base max-w-full">
              <span className="whitespace-nowrap">Paid Amount:</span>
              <div className="w-full sm:w-[65%] flex items-center justify-between gap-2 max-w-full overflow-x-hidden">
                <Payments totalCalculator={totalCalculator} />
              </div>
            </div>
            <Form.Item style={{ marginTop: "15px" }} className="max-w-full">
              <Button
                block
                type="primary"
                htmlType="submit"
                loading={loader}
                onClick={() => setLoader(true)}
                className="w-full max-w-full">
                Create Purchase
              </Button>
            </Form.Item>
          </div>
        </div>
      </div>
    </Form>
    
  );
};

export default AddPurchase;
