import { CheckCircleFilled } from "@ant-design/icons";
import {
  Button,
  Form,
  Input,
  InputNumber,
  message,
  notification,
  Select,
} from "antd";
import React, { FC, useEffect, useState } from "react";
import MediaQuery, { useMediaQuery } from "react-responsive";
import styles from "./myQuotation.module.scss";
import cx from "classnames";
import { useRouter } from "next/router";
import * as QuotationAPI from "../../../pages/api/profile";
import _ from "lodash";
import { Message, QuotationData, updateForm } from "./quotation";
import { GrSend } from "react-icons/gr";
import { FiSearch } from "react-icons/fi";
import { RiSendPlaneFill } from "react-icons/ri";
import MyQuotation from "./myQuotation";


export const EditQuotePage: FC<any> = ({id}) => {
  const [form] = Form.useForm();
  const isMobile = useMediaQuery({ maxWidth: 767.68 });
  const width = isMobile ? 320 : 600;
  const fontsize = isMobile ? 10 : 20;
  const desfontsize = isMobile ? 10 : 14;
  const [editFormData, setEditFormData] = useState<any>("");
  const [qouteId, setqouteId] = useState<any>("");
  const [productsNum, setproductsNum] = useState<any>();
  const [token, setToken] = useState("");
  const router = useRouter();
  const [chartMessage, setchartMessage] = useState<string>("");
  const [numberofProducts, setnumberofProducts] = useState<number>(0);
  const [priceofeachProduct, setPriceofeachProduct] = useState<number>(0);
  const [validationpriceofeachProduct, setvalidationpriceofeachProduct] =
    useState<string>("");
  const [description, setDescription] = useState<string>("");
  const [isBack, setIsBack] = useState(false);

  useEffect(() => {
    const val: any = localStorage.getItem("loginDetails");
    const details = JSON.parse(val);
    const authtoken: any = !_.isEmpty(details) ? details.token : null;
    setToken(authtoken);
    setqouteId(id);
    if (id) getEditQuotationList(authtoken);
  }, []);
  const isBackHandler = () => {
    setIsBack(true);
    
  };


  const getEditQuotationList = async (token: string) => {
    QuotationAPI.getEditQuotationData(token, id).then(
      (res) => {
        setEditFormData(res.data);
        form.setFieldsValue({
          NumberofProducts: res.data.number_of_products,
          PriceofeachProduct:
            res.data.status == "approved"
              ? res.data.seller_offer_price
              : res.data.customer_offer_price,
          description: res.data.description,
        });
        setnumberofProducts(res.data.number_of_products);
        setPriceofeachProduct(res.data.customer_offer_price);
        setvalidationpriceofeachProduct(res.data.price_of_each_product);
        setDescription(res.data.description);
      }
    );
  };

  const onFinish = (values: updateForm) => {
    updateQuote(values);
  };

  const onFinishFailed = () => {
    message.warn("Please fill all fields of the request form!!");
  };

  const validateMessages = {
    required: "${label} is required!",
  };

  const updateQuote = (values: updateForm) => {
    const paylod: QuotationData = {
      product_id: editFormData.product_id,
      price_of_each_product: editFormData.price_of_each_product,
      description: values.description,
      customer_offer_price: `${values.PriceofeachProduct}`,
      number_of_products: values.NumberofProducts,
      expected_delivery: editFormData.expected_delivery,
      customer_status: values.status,
    };

    QuotationAPI.UpdateQuotationData(paylod, token, editFormData.id)
      .then((res) => {
        if (res && res.data.message == "Quote updated successfully.") {
          notification.open({
            type: "success",
            message: (
              <div
                style={{
                  color: "#291C61",
                  fontSize: fontsize,
                  fontFamily: "Outfit",
                }}
              >
                Your quote request submitted successfully!
              </div>
            ),
            description: (
              <div
                style={{
                  color: "#291C61",
                  fontSize: desfontsize,
                  fontFamily: "Outfit",
                }}
              >
                We will update you once got response from the Vendor.
              </div>
            ),
            style: {
              width: width,
              minWidth: 320,
              maxWidth: 568,
              backgroundColor: "#F6FFED",
              border: "1px solid #B7EB8F",
              margin: 0,
              boxShadow: "unset",
              color: "#291C61",
            },
            icon: <CheckCircleFilled style={{ color: "#52C51A" }} />,
          });
        } else {
          notification.open({
            type: "error",
            message: (
              <div
                style={{
                  color: "#291C61",
                  fontSize: fontsize,
                  fontFamily: "Outfit",
                }}
              >
                Quote request sumission Failed!!
              </div>
            ),
            description: (
              <div
                style={{
                  color: "#291C61",
                  fontSize: desfontsize,
                  fontFamily: "Outfit",
                }}
              >
                Please try again after Sometime.
              </div>
            ),
            style: {
              width: width,
              minWidth: 320,
              maxWidth: 568,
              backgroundColor: "pink",
              border: "1px solid #B7EB8F",
              margin: 0,
              boxShadow: "unset",
              color: "#291C61",
            },
          });
        }
        form.resetFields();
        getEditQuotationList(token);
        router.push(
          {
            pathname: `/customerDashboard/customerDashboard`,
            query: { val: "My Quotations" },
          },
          `/customerDashboard/customerDashboard`
        );
      })
      .catch((error) => {
        notification.open({
          type: "error",
          message: (
            <div
              style={{
                color: "#291C61",
                fontSize: fontsize,
                fontFamily: "Outfit",
              }}
            >
              Quote request sumission Failed!!
            </div>
          ),
          description: (
            <div
              style={{
                color: "#291C61",
                fontSize: desfontsize,
                fontFamily: "Outfit",
              }}
            >
              Please try again after Sometime.
            </div>
          ),
          style: {
            width: width,
            minWidth: 320,
            maxWidth: 568,
            backgroundColor: "pink",
            border: "1px solid #B7EB8F",
            margin: 0,
            boxShadow: "unset",
            color: "#291C61",
          },
        });
      });
  };

  const sendMessage = (value: string) => {
    const paylod: Message = {
      message: value,
      quote_id: editFormData.id,
    };

    QuotationAPI.sendMessage(token, paylod, editFormData.id).then((res) => {
      if (res && res.data.message == "Quote Message created successfully.") {
        notification.open({
          type: "success",
          message: (
            <div
              style={{
                color: "#291C61",
                fontSize: fontsize,
                fontFamily: "Outfit",
              }}
            >
              Message Sent Successfully!
            </div>
          ),
          style: {
            width: width,
            minWidth: 320,
            maxWidth: 568,
            backgroundColor: "#F6FFED",
            border: "1px solid #B7EB8F",
            margin: 0,
            boxShadow: "unset",
            color: "#291C61",
          },
          icon: <CheckCircleFilled style={{ color: "#52C51A" }} />,
        });
      } else {
        notification.open({
          type: "error",
          message: (
            <div
              style={{
                color: "#291C61",
                fontSize: fontsize,
                fontFamily: "Outfit",
              }}
            >
              Quote request sumission Failed!!
            </div>
          ),
          description: (
            <div
              style={{
                color: "#291C61",
                fontSize: desfontsize,
                fontFamily: "Outfit",
              }}
            >
              Please try again after Sometime.
            </div>
          ),
          style: {
            width: width,
            minWidth: 320,
            maxWidth: 568,
            backgroundColor: "pink",
            border: "1px solid #B7EB8F",
            margin: 0,
            boxShadow: "unset",
            color: "#291C61",
          },
        });
      }
      setchartMessage("");
      getEditQuotationList(token);
      // router.push(
      //   {
      //     pathname: `/customerDashboard/customerDashboard`,
      //     query: { val: "My Quotations" },
      //   },
      //   `/customerDashboard/customerDashboard`
      // );
    });
  };

  const validation = (rule: any, value: any, callback: any) => {
    if (parseFloat(value) > parseFloat(validationpriceofeachProduct)) {
      callback(
        `Price of each product cannot be more than ₹${parseFloat(
          validationpriceofeachProduct
        ).toFixed(2)}`
      );
    } else if (value && parseFloat(value) <= 0) {
      callback(`Price of each product cannot be less than 1`);
    } else {
      callback();
    }
  };
if (!isBack) {
  return (
    <>
      <div className={cx(styles.detailsQuoteContainer)}>
      <div className="ant-row my-4">
            <div className={cx(styles.h1Styles, "ant-col-xl-22 ant-col-xs-16  pl-1")}>
            View Quotes Details
            </div>
            <div className="ant-col-xl-2 ant-col-xs-8 px-4 cursor-pointer">
              <span onClick={isBackHandler}>&#60; Back</span>
            </div>
          </div>
        
        <div className={styles.boxContainer}>
          <div
            style={{
              boxShadow: "0px 4px 40px rgba(0, 0, 0, 0.06)",
              padding: "2em",
            }}
          >
            <h1
              style={{
                fontFamily: "Outfit",
                fontStyle: "normal",
                fontWeight: 600,
                fontSize: "26px",
                lineHeight: "20px",
                color: "#291C61",
              }}
            >
              Quote Details
            </h1>
            <div>
              <MediaQuery maxWidth={769}>
                <Form
                  form={form}
                  layout="vertical"
                  onFinish={onFinish}
                  onFinishFailed={onFinishFailed}
                  validateMessages={validateMessages}
                  autoComplete="off"
                >
                  <div className={styles.formContainer}>
                    <div className={styles.InputBox}>
                      <Form.Item
                        name="NumberofProducts"
                        label="Number of Products"
                        rules={[
                          {
                            required: true,
                          },
                          // {
                          //   pattern: new RegExp(
                          //     /^(2[0-9]|[3-9][0-9]|[1-9][0-9]{2,6})$/
                          //   ),
                          //   message: "Minimum quote quantity is 20",
                          // },
                          {
                            pattern: new RegExp(/^[1-9][0-9]*$/),
                            message: "Minimum quote quantity is 1",
                          },
                        ]}
                      >
                        <InputNumber
                          style={{ width: "100%" }}
                          readOnly={
                            editFormData.customer_status &&
                            Array.isArray(editFormData.customer_status)
                          }
                        />
                      </Form.Item>
                      <Form.Item
                        name="PriceofeachProduct"
                        label="Price of each Product"
                        rules={[
                          { required: true },
                          {
                            validator: validation,
                          },
                        ]}
                      >
                        <InputNumber
                          style={{ width: "100%" }}
                          readOnly={
                            editFormData.customer_status &&
                            Array.isArray(editFormData.customer_status)
                          }
                        />
                      </Form.Item>
                      <Form.Item
                        name="description"
                        label="Description"
                        rules={[{ required: true }, { type: "string", min: 5 }]}
                      >
                        <Input.TextArea
                          placeholder="Need 25 quantity of this product @90 each"
                          readOnly={
                            editFormData.customer_status &&
                            Array.isArray(editFormData.customer_status)
                          }
                        />
                      </Form.Item>
                      {editFormData.customer_status &&
                      Array.isArray(editFormData.customer_status) ? (
                        <div className={styles.messageBoxContainer}>
                          <Form.Item
                            name="status"
                            label="Accept / Reject Quote"
                            rules={[
                              { required: true },
                              { type: "string", min: 1 },
                            ]}
                          >
                            <Select
                              size="large"
                              placeholder={
                                editFormData.customer_selected_status &&
                                editFormData.customer_selected_status.toLowerCase() ==
                                  "accepted"
                                  ? "Accepted"
                                  : "Please Select"
                              }
                              disabled={
                                editFormData.customer_selected_status &&
                                editFormData.customer_selected_status.toLowerCase() ==
                                  "accepted"
                              }
                            >
                              {editFormData.customer_status.map(
                                (status: string, idx: number) => (
                                  <Select.Option value={status} key={idx + 1}>
                                    {status.charAt(0).toUpperCase() +
                                      status.slice(1)}
                                  </Select.Option>
                                )
                              )}
                            </Select>
                          </Form.Item>
                        </div>
                      ) : (
                        <></>
                      )}
                      <Form.Item>
                        <Button
                          type="primary"
                          htmlType="submit"
                          style={{ width: "100%", height: "4em" }}
                          disabled={
                            editFormData.customer_selected_status &&
                            editFormData.customer_selected_status.toLowerCase() ==
                              "accepted"
                          }
                        >
                          <a
                            style={{
                              fontFamily: "Outfit",
                              fontSize: "16px",
                              lineHeight: "20px",
                            }}
                          >
                            Update Quote
                          </a>
                        </Button>
                      </Form.Item>
                    </div>
                  </div>
                </Form>
              </MediaQuery>

              <MediaQuery minWidth={769}>
                <Form
                  form={form}
                  layout="vertical"
                  onFinish={onFinish}
                  onFinishFailed={onFinishFailed}
                  validateMessages={validateMessages}
                  autoComplete="off"
                >
                  <div className={styles.formContainer}>
                    <div className={styles.InputBox}>
                      <Form.Item
                        name="NumberofProducts"
                        label="Number of Products"
                        rules={[
                          {
                            required: true,
                          },
                          {
                            pattern: new RegExp(/^[1-9][0-9]*$/),
                            message: "Minimum quote quantity is 1",
                          },
                        ]}
                      >
                        <InputNumber
                          style={{ width: "100%" }}
                          size="large"
                          readOnly={
                            editFormData.customer_status &&
                            Array.isArray(editFormData.customer_status)
                          }
                        />
                      </Form.Item>
                      <Form.Item
                        name="PriceofeachProduct"
                        label="Price of each Product"
                        rules={[
                          { required: true },
                          {
                            validator: validation,
                          },
                        ]}
                      >
                        <InputNumber
                          style={{ width: "100%" }}
                          size="large"
                          readOnly={
                            editFormData.customer_status &&
                            Array.isArray(editFormData.customer_status)
                          }
                        />
                      </Form.Item>
                      <Form.Item
                        name="description"
                        label="Description"
                        rules={[
                          { required: true },
                          { type: "string", min: 5, max: 160 },
                        ]}
                      >
                        <Input.TextArea
                          maxLength={160}
                          showCount
                          placeholder="Need 25 quantity of this product @90 each"
                          style={{ height: "125px" }}
                          readOnly={
                            editFormData.customer_status &&
                            Array.isArray(editFormData.customer_status)
                          }
                        />
                      </Form.Item>

                      {editFormData.customer_status &&
                      Array.isArray(editFormData.customer_status) ? (
                        <div className={styles.messageBoxContainer}>
                          <Form.Item
                            name="status"
                            label="Accept / Reject Quote"
                            rules={[
                              { required: true },
                              { type: "string", min: 1 },
                            ]}
                          >
                            <Select
                              size="large"
                              placeholder={
                                editFormData.customer_selected_status &&
                                editFormData.customer_selected_status.toLowerCase() ==
                                  "accepted"
                                  ? "Accepted"
                                  : "Please Select"
                              }
                              disabled={
                                editFormData.customer_selected_status &&
                                editFormData.customer_selected_status.toLowerCase() ==
                                  "accepted"
                              }
                            >
                              {editFormData.customer_status.map(
                                (status: string, idx: number) => (
                                  <Select.Option value={status} key={idx + 1}>
                                    {status.charAt(0).toUpperCase() +
                                      status.slice(1)}
                                  </Select.Option>
                                )
                              )}
                            </Select>
                          </Form.Item>
                        </div>
                      ) : (
                        <></>
                      )}

                      <Form.Item>
                        <Button
                          type="primary"
                          htmlType="submit"
                          style={{ width: "100%", height: "4em" }}
                          disabled={
                            editFormData.customer_selected_status &&
                            editFormData.customer_selected_status.toLowerCase() ==
                              "accepted"
                          }
                        >
                          <a
                            style={{
                              fontFamily: "Outfit",
                              fontSize: "16px",
                              lineHeight: "20px",
                            }}
                          >
                            Update Quote
                          </a>
                        </Button>
                      </Form.Item>
                    </div>
                  </div>
                </Form>
              </MediaQuery>
            </div>
          </div>

          <div className={styles.chartBoxContainer}>
            <h1 className={styles.chartBoxTitle}>Quote Conversation</h1>
            <div className={styles.messageSendBoxContainer}>
              <div className={styles.chartMessageBoxContainer}>
                {editFormData.quote_message &&
                  editFormData.quote_message.message.map(
                    (messages: any, i: number) => {
                      return (
                        <React.Fragment key={i}>
                          {messages.query && messages.query != "" ? (
                            <>
                              {messages.customer_name ? (
                                <div className={styles.chartsBoxCustomer}>
                                  <span className={styles.charts}>
                                    {messages.query}
                                  </span>
                                  <span className={styles.chartTime}>
                                    {messages.sent_at}
                                  </span>
                                </div>
                              ) : (
                                <div className={styles.chartsBoxCustomerSeller}>
                                  <span className={styles.sellerCharts}>
                                    <p>{messages.query}</p>

                                    <a className={styles.sellerName}>
                                      {messages.seller_name}
                                    </a>
                                  </span>
                                  <span className={styles.chartTime}>
                                    {messages.sent_at}
                                  </span>
                                </div>
                              )}
                            </>
                          ) : (
                            <></>
                          )}
                        </React.Fragment>
                      );
                    }
                  )}
              </div>
              <div className={styles.chartMessageSendContainer}>
                <Input.Group
                  compact
                  style={{ display: "flex", flexDirection: "row" }}
                >
                  <Input
                    size="large"
                    placeholder="Write Your Message"
                    maxLength={160}
                    value={chartMessage}
                    onChange={(e) => setchartMessage(e.target.value)}
                    name="message"
                  />
                  <Button
                    type="primary"
                    onClick={() => {
                      sendMessage(chartMessage);
                    }}
                    size={"large"}
                  >
                    <RiSendPlaneFill style={{ fontSize: "1.5em" }} />
                  </Button>
                </Input.Group>
              </div>
            </div>
          </div>
        </div>
      </div>
    </>
  );
} else {
  return <MyQuotation />;
}
};

export default EditQuotePage;
