'use client'

import { Icon } from '@iconify/react'
import { useEffect, useState } from 'react'
import { cn } from '@/lib/utils'
import {
  OPEN_WHATSAPP_MODAL_EVENT,
  WhatsAppModal,
  type WhatsAppBranch
} from '@/components/layout/whatsapp-modal'

interface WhatsAppButtonProps {
  whatsapp?: string | null
  domainName?: string | null
  branches?: WhatsAppBranch[] | null
}

export function WhatsAppButton({ whatsapp, domainName, branches }: WhatsAppButtonProps) {
  const [isVisible, setIsVisible] = useState(false)
  const [isModalOpen, setIsModalOpen] = useState(false)

  useEffect(() => {
    // Show button after a small delay or on scroll
    const timer = setTimeout(() => setIsVisible(true), 1500)
    return () => clearTimeout(timer)
  }, [])

  useEffect(() => {
    const handleOpenModal = () => setIsModalOpen(true)
    window.addEventListener(OPEN_WHATSAPP_MODAL_EVENT, handleOpenModal)
    return () => window.removeEventListener(OPEN_WHATSAPP_MODAL_EVENT, handleOpenModal)
  }, [])

  return (
    <>
      {whatsapp && (
        <button
          type='button'
          onClick={() => setIsModalOpen(true)}
          className={cn(
            'btn_whatsapp fixed bottom-6 right-6 sm:bottom-[30px] sm:right-[40px] z-[100] inline-flex items-center justify-center rounded-[50px] bg-[#1ab600] px-4 py-2.5 sm:px-5 sm:py-2.5 text-white shadow-[0_8px_24px_rgba(0,0,0,0.2)] transition-all duration-500 hover:bg-[#159600] hover:scale-105 active:scale-95 cursor-pointer',
            isVisible ? 'translate-y-0 opacity-100' : 'translate-y-20 opacity-0'
          )}
          aria-label='Chat Sekarang! Konsultasi Gratis'
        >
          <Icon
            icon='ic:baseline-whatsapp'
            className='btn_whatsapp pointer-events-none mr-1.5 sm:mr-3 h-[24px] w-[24px] sm:h-[27px] sm:w-[27px] shrink-0'
          />
          <span className='btn_whatsapp pointer-events-none text-xs sm:text-sm font-normal leading-[1.2] whitespace-nowrap'>
            Chat Sekarang! Konsultasi Gratis
          </span>
        </button>
      )}

      <WhatsAppModal
        open={isModalOpen}
        onClose={() => setIsModalOpen(false)}
        whatsapp={whatsapp}
        domainName={domainName}
        branches={branches}
      />
    </>
  )
}
