import { useEffect, useState } from 'react';
import { track } from '../lib/analytics';
import {
  getCustomerServicePhone,
  loadCustomerServicePhone,
  openWecomCustomerService,
} from '../lib/customer-service';

type ContactCustomerSheetProps = {
  orderId?: string;
  orderNo?: string;
  onClose: () => void;
};

export default function ContactCustomerSheet({ orderId, onClose }: ContactCustomerSheetProps) {
  const [phone, setPhone] = useState(getCustomerServicePhone);

  useEffect(() => {
    void loadCustomerServicePhone().then(setPhone);
  }, []);

  const tel = phone.replace(/-/g, '');

  function openPhone() {
    track('cs_contact', { type: 'phone', orderId });
    window.location.href = `tel:${tel}`;
    onClose();
  }

  function openOnline() {
    track('cs_contact', { type: 'wecom_kf', orderId });
    if (openWecomCustomerService()) {
      onClose();
    }
  }

  return (
    <div className="contact-customer-overlay" onClick={onClose}>
      <div className="contact-customer-sheet" onClick={(e) => e.stopPropagation()}>
        <div className="contact-customer-head">
          <h3>联系客服</h3>
          <button type="button" className="contact-customer-close" aria-label="关闭" onClick={onClose}>
            <span className="material-symbols-outlined">close</span>
          </button>
        </div>

        <div className="contact-customer-options">
          <button type="button" className="contact-customer-option" onClick={openPhone}>
            <div className="contact-customer-option-icon">
              <span className="material-symbols-outlined">call</span>
            </div>
            <div className="contact-customer-option-body">
              <p className="contact-customer-option-title">拨打总部客服电话</p>
              <p className="contact-customer-option-sub">{phone}</p>
            </div>
            <span className="material-symbols-outlined contact-customer-chevron">chevron_right</span>
          </button>

          <button type="button" className="contact-customer-option" onClick={openOnline}>
            <div className="contact-customer-option-icon">
              <span className="material-symbols-outlined">chat</span>
            </div>
            <div className="contact-customer-option-body">
              <p className="contact-customer-option-title">在线客服</p>
              <p className="contact-customer-option-sub">专业客服实时解答</p>
            </div>
            <span className="material-symbols-outlined contact-customer-chevron">chevron_right</span>
          </button>
        </div>

        <button type="button" className="contact-customer-cancel" onClick={onClose}>
          取消
        </button>
      </div>
    </div>
  );
}
