import { CopyFilled } from "@ant-design/icons";
import { Button, Form, message, Popover, Space } from "antd";
import axios from "axios";
import Dinero from "dinero.js";
import { ParseError, parsePhoneNumberWithError } from "libphonenumber-js";
import { useState } from "react";
import { useTranslation } from "react-i18next";
import { connect } from "react-redux";
import { createStructuredSelector } from "reselect";
import { openChatByPhone, setMessage } from "../../redux/messaging/messaging.actions";
import { selectBodyshop, selectCurrentUser } from "../../redux/user/user.selectors";
import CurrencyFormItemComponent from "../form-items-formatted/currency-form-item.component";
import { useSocket } from "../../contexts/SocketIO/useSocket.js";

const mapStateToProps = createStructuredSelector({
  bodyshop: selectBodyshop,
  currentUser: selectCurrentUser
});
const mapDispatchToProps = (dispatch) => ({
  openChatByPhone: (phone) => dispatch(openChatByPhone(phone)),
  setMessage: (text) => dispatch(setMessage(text))
});
export default connect(mapStateToProps, mapDispatchToProps)(PaymentsGenerateLink);

export function PaymentsGenerateLink({ bodyshop, currentUser, callback, job, openChatByPhone, setMessage }) {
  const { t } = useTranslation();
  const [form] = Form.useForm();

  const [open, setOpen] = useState(false);
  const [loading, setLoading] = useState(false);
  const [paymentLink, setPaymentLink] = useState(null);
  const { socket } = useSocket();

  const handleFinish = async ({ amount }) => {
    setLoading(true);
    let p;
    try {
      // Updated to use parsePhoneNumberWithError
      p = parsePhoneNumberWithError(job.ownr_ph1 || "", "CA");
    } catch (error) {
      if (error instanceof ParseError) {
        // Handle specific parsing errors
        console.log(`Phone number parsing failed: ${error.message}`);
      } else {
        // Handle other unexpected errors
        console.log("Unexpected error while parsing phone number:", error);
      }
    }
    setLoading(true);
    const response = await axios.post("/intellipay/generate_payment_url", {
      bodyshop,
      amount: amount,
      account: job.ro_number,
      comment: btoa(
        JSON.stringify({
          payments: [{ jobid: job.id, amount }],
          userEmail: currentUser.email
        })
      )
    });
    setLoading(false);
    setPaymentLink(response.data.shorUrl);

    if (p) {
      openChatByPhone({
        phone_num: p.formatInternational(),
        jobid: job.id,
        socket
      });
      setMessage(
        t("payments.labels.smspaymentreminder", {
          shopname: bodyshop.shopname,
          amount: amount,
          payment_link: response.data.shorUrl
        })
      );
    }

    //Add in confirmation & errors.
    if (callback) callback();

    // setOpen(false);
    setLoading(false);
  };

  const popContent = (
    <div>
      <Form onFinish={handleFinish} layout="vertical" form={form}>
        <Form.Item
          label={t("payments.fields.amount")}
          rules={[
            {
              required: true
              //message: t("general.validation.required"),
            }
          ]}
          name="amount"
        >
          <CurrencyFormItemComponent />
        </Form.Item>
        {paymentLink && (
          <Space orientation="vertical">
            <Space
              style={{ cursor: "pointer" }}
              onClick={() => {
                navigator.clipboard.writeText(paymentLink);
                message.success(t("general.actions.copied"));
              }}
            >
              <div
                onClick={() => {
                  //Copy the link.
                }}
              >
                {paymentLink}
              </div>{" "}
              <CopyFilled />
            </Space>
            <Button
              onClick={() => {
                let p;
                try {
                  // Updated second instance of phone parsing
                  p = parsePhoneNumberWithError(job.ownr_ph1, "CA");
                } catch (error) {
                  if (error instanceof ParseError) {
                    // Handle specific parsing errors
                    console.log(`Phone number parsing failed: ${error.message}`);
                  } else {
                    // Handle other unexpected errors
                    console.log("Unexpected error while parsing phone number:", error);
                  }
                  return;
                }
                openChatByPhone({
                  phone_num: p.formatInternational(),
                  jobid: job.id,
                  socket
                });
                setMessage(
                  t("payments.labels.smspaymentreminder", {
                    shopname: bodyshop.shopname,
                    amount: Dinero({
                      amount: Math.round(form.getFieldValue("amount") * 100)
                    }).toFormat(),
                    payment_link: paymentLink
                  })
                );
              }}
            >
              {t("general.actions.sendbysms")}
            </Button>
          </Space>
        )}
      </Form>
      <Space>
        <Button type="primary" onClick={() => form.submit()}>
          {t("general.actions.submit")}
        </Button>
        <Button
          onClick={() => {
            form.resetFields();
            setPaymentLink(null);
            setOpen(false);
          }}
        >
          {t("general.actions.cancel")}
        </Button>
      </Space>
    </div>
  );

  return (
    <Popover content={popContent} open={open}>
      <Button onClick={() => setOpen(true)} loading={loading}>
        {t("payments.actions.generatepaymentlink")}
      </Button>
    </Popover>
  );
}
