import { Button } from "antd";
import parsePhoneNumber from "libphonenumber-js";
import { useCallback, useMemo } from "react";
import { useTranslation } from "react-i18next";
import { connect } from "react-redux";
import { createStructuredSelector } from "reselect";
import { openChatByPhone } from "../../redux/messaging/messaging.actions";
import { selectBodyshop } from "../../redux/user/user.selectors";
import { searchingForConversation } from "../../redux/messaging/messaging.selectors";
import { useSocket } from "../../contexts/SocketIO/useSocket.js";
import { useNotification } from "../../contexts/Notifications/notificationContext.jsx";
import PhoneNumberFormatter from "../../utils/PhoneFormatter";

const mapStateToProps = createStructuredSelector({
  bodyshop: selectBodyshop,
  searchingForConversation
});

const mapDispatchToProps = (dispatch) => ({
  openChatByPhone: (payload) => dispatch(openChatByPhone(payload))
});

export function ChatOpenButton({ bodyshop, searchingForConversation, phone, type, jobid, openChatByPhone }) {
  const { t } = useTranslation();
  const { socket } = useSocket();
  const notification = useNotification();

  if (!phone) return null;

  const messagingEnabled = Boolean(bodyshop?.messagingservicesid);

  const parsed = useMemo(() => {
    if (!messagingEnabled) return null;
    try {
      return parsePhoneNumber(phone, "CA") || null;
    } catch {
      return null;
    }
  }, [messagingEnabled, phone]);

  const isValid = Boolean(parsed?.isValid?.() && parsed.isValid());
  const clickable = messagingEnabled && !searchingForConversation && isValid;

  const onClick = useCallback(
    (e) => {
      e.preventDefault();
      e.stopPropagation();

      if (!messagingEnabled) return;
      if (searchingForConversation) return;

      if (!isValid) {
        notification.error({ title: t("messaging.error.invalidphone") });
        return;
      }

      openChatByPhone({
        phone_num: parsed.formatInternational(),
        jobid,
        socket
      });
    },
    [messagingEnabled, searchingForConversation, isValid, parsed, jobid, socket, openChatByPhone, notification, t]
  );

  const content = <PhoneNumberFormatter type={type}>{phone}</PhoneNumberFormatter>;

  // If not clickable, render plain formatted text (no link styling)
  if (!clickable) return content;

  // Clickable: render as a link-styled button (best for a “command”)
  return (
    <Button
      type="link"
      onClick={onClick}
      className="chat-open-button-link"
      aria-label={t("messaging.actions.openchat") || "Open chat"}
    >
      {content}
    </Button>
  );
}

export default connect(mapStateToProps, mapDispatchToProps)(ChatOpenButton);
