import { useCallback, useEffect, useRef, useState } from 'react'
import { MobileCenterModal } from '@/components/mobile-center-modal.tsx'
import { DataLoadingIndicator } from '@/components/ui/data-loading-indicator'
import { useModalStore } from '@/store'

const SUPPORT_CHAT_URL =
  'https://tawk.to/chat/6a1d23d9e29f411c2ce86772/1jq0t82lu'
const IFRAME_READY_DELAY_MS = 2_000

function MobileSupportModal() {
  const [isLoading, setIsLoading] = useState(true)
  const readyTimerRef = useRef<number | null>(null)
  const open = useModalStore((state) => state.modals.desktopSupport)
  const setModalOpen = useModalStore((state) => state.setModalOpen)

  const clearReadyTimer = useCallback(() => {
    if (readyTimerRef.current === null) {
      return
    }

    window.clearTimeout(readyTimerRef.current)
    readyTimerRef.current = null
  }, [])

  const handleClose = () => {
    setModalOpen('desktopSupport', false)
  }

  const handleLoaded = () => {
    clearReadyTimer()
    readyTimerRef.current = window.setTimeout(() => {
      setIsLoading(false)
      readyTimerRef.current = null
    }, IFRAME_READY_DELAY_MS)
  }

  useEffect(() => {
    if (open) {
      clearReadyTimer()
      setIsLoading(true)
    }

    return clearReadyTimer
  }, [clearReadyTimer, open])

  return (
    <MobileCenterModal
      open={open}
      isNormalBg={true}
      onClose={handleClose}
      titleAlign="left"
      title={<div className="modal-title-glow text-design-16">在线客服</div>}
      className="h-design-500"
    >
      <div className="h-full min-h-0 px-design-8 pb-design-10 pt-design-4">
        <div className="relative h-full min-h-0 overflow-hidden rounded-[calc(var(--design-unit)*7)] border border-[#2A6D73] bg-[linear-gradient(180deg,rgba(5,22,31,0.98),rgba(2,10,17,0.98))] shadow-[inset_0_0_calc(var(--design-unit)*14)_rgba(88,205,218,0.13),0_0_calc(var(--design-unit)*10)_rgba(31,156,174,0.14)]">
          {isLoading ? (
            <div className="absolute inset-0 z-10 flex items-center justify-center bg-[radial-gradient(circle_at_center,rgba(20,92,105,0.38),rgba(2,10,17,0.98)_58%)]">
              <DataLoadingIndicator
                label="客服连线中"
                className="text-design-12"
              />
            </div>
          ) : null}
          <iframe
            title="customer-service-chat"
            src={SUPPORT_CHAT_URL}
            onLoad={handleLoaded}
            className="h-full w-full bg-[linear-gradient(180deg,#061923,#020A11)]"
            allow="microphone; camera; clipboard-read; clipboard-write"
          />
        </div>
      </div>
    </MobileCenterModal>
  )
}

export default MobileSupportModal
