import { useState, memo, useCallback, useMemo } from "react";
import { ArrowRight, Headset } from "lucide-react";
import CallDialog from "./CallDialog";

interface HeaderWithSupportProps {
  title: string;
  onBack: () => void;
  hideSupportButton?: boolean;
}

const HeaderWithSupport = memo(function HeaderWithSupport({
  title,
  onBack,
  hideSupportButton,
}: HeaderWithSupportProps) {
  const [isCallModalOpen, setIsCallModalOpen] = useState(false);
  const supportPhone = useMemo(
    () => import.meta.env.VITE_SUPPORT_PHONE || "",
    []
  );

  const handleSupportClick = useCallback(() => {
    setIsCallModalOpen(true);
  }, []);

  const handleCallConfirm = useCallback(() => {
    window.location.href = `tel:${supportPhone}`;
    setIsCallModalOpen(false);
  }, [supportPhone]);

  const handleKeyDown = useCallback(
    (e: React.KeyboardEvent) => {
      if (e.key === "Enter") {
        handleSupportClick();
      }
    },
    [handleSupportClick]
  );

  return (
    <>
      {/* Mobile only — on desktop the dashboard sidebar / desktop header stands
          in for this back+support bar. */}
      <div className="lg:hidden sticky top-0 z-30 bg-WHITE pt-[env(safe-area-inset-top)]">
        <div className="relative flex flex-row h-[65px] bg-WHITE w-full items-center justify-center border-b border-inner-border">
          <ArrowRight
            onClick={onBack}
            className="absolute top-5 right-5 cursor-pointer"
          />
          <p className="text-B16 font-bold ">{title}</p>
          {!hideSupportButton && (
            <div
              className="absolute top-4 h-8 w-8 left-5 rounded-full bg-WHITE shadow-xl flex items-center justify-center cursor-pointer"
              onClick={handleSupportClick}
              role="button"
              tabIndex={0}
              onKeyDown={handleKeyDown}
            >
              <Headset size={20} />
            </div>
          )}
        </div>
      </div>

      <CallDialog
        isCallModalOpen={isCallModalOpen}
        setIsCallModalOpen={setIsCallModalOpen}
        handleCallConfirm={handleCallConfirm}
      />
    </>
  );
});

export default HeaderWithSupport;
