'use client'

import { useEffect } from 'react'
import { Icon } from '@iconify/react'

export interface WhatsAppBranch {
  id: number
  contact_category?: string | null
  city: string
  mobile_phone: string
  mobile_phone_text?: string | null
  description?: string | null
  status?: number
  default?: number
}

export const DEFAULT_WHATSAPP_BRANCHES: WhatsAppBranch[] = [
  {
    id: 1,
    contact_category: 'window_fashion',
    city: 'Jakarta',
    mobile_phone: '628131427858',
    mobile_phone_text: '0813-1427-858',
    status: 1,
    default: 1
  },
  {
    id: 2,
    contact_category: 'window_fashion',
    city: 'Tangerang',
    mobile_phone: '6282298357188',
    mobile_phone_text: '0822-9835-7188',
    status: 1,
    default: 1
  },
  {
    id: 3,
    contact_category: 'window_fashion',
    city: 'Bekasi',
    mobile_phone: '628131427858',
    mobile_phone_text: '0813-1427-858',
    status: 1,
    default: 1
  },
  {
    id: 4,
    contact_category: 'window_fashion',
    city: 'Bandung',
    mobile_phone: '6281224662316',
    mobile_phone_text: '0812-2466-2316',
    status: 1,
    default: 1
  }
]

export const OPEN_WHATSAPP_MODAL_EVENT = 'open-whatsapp-modal'

export function openWhatsAppModal() {
  if (typeof window !== 'undefined') {
    window.dispatchEvent(new CustomEvent(OPEN_WHATSAPP_MODAL_EVENT))
  }
}

interface WhatsAppModalProps {
  open: boolean
  onClose: () => void
  whatsapp?: string | null
  domainName?: string | null
  branches?: WhatsAppBranch[] | null
}

function resolveGreeting(whatsapp?: string | null, domainName?: string | null): string {
  if (whatsapp && whatsapp.startsWith('http')) {
    try {
      const url = new URL(whatsapp)
      const textParam = url.searchParams.get('text')
      if (textParam) {
        return textParam
      }
    } catch {
      // Fallback if URL parsing fails
    }
  }
  return `Hi ${domainName || 'Homipedia'}`
}

export function WhatsAppModal({
  open,
  onClose,
  whatsapp,
  domainName,
  branches
}: WhatsAppModalProps) {
  useEffect(() => {
    if (!open) return

    const handleKeyDown = (e: KeyboardEvent) => {
      if (e.key === 'Escape') {
        onClose()
      }
    }

    window.addEventListener('keydown', handleKeyDown)
    return () => window.removeEventListener('keydown', handleKeyDown)
  }, [open, onClose])

  if (!open) return null

  const items = branches && branches.length > 0 ? branches : DEFAULT_WHATSAPP_BRANCHES

  const handleBranchClick = (item: WhatsAppBranch) => {
    let phoneNumber = (item.mobile_phone || '').replace(/\D/g, '')
    if (phoneNumber.startsWith('0')) {
      phoneNumber = '62' + phoneNumber.slice(1)
    }

    const textGreeting =
      item.description?.trim() || resolveGreeting(whatsapp, domainName)
    window.open(
      `https://api.whatsapp.com/send?phone=${phoneNumber}&text=${encodeURIComponent(textGreeting)}`,
      '_blank'
    )
  }

  return (
    <div
      className='fixed inset-0 z-[200] flex items-center justify-center bg-black/50 p-4 backdrop-blur-[1px]'
      onClick={onClose}
    >
      <div
        className='relative w-full max-w-[600px] rounded-2xl bg-white px-6 pt-6 pb-4 text-zinc-900 shadow-2xl'
        onClick={e => e.stopPropagation()}
      >
        <div className='flex w-full flex-col items-center justify-center space-y-2'>
          <h2 className='text-center text-2xl font-bold text-zinc-900'>WA Center Homipedia</h2>
          <p className='pb-4 text-center text-sm text-zinc-600'>
            Pilih cabang yang dekat dengan lokasi anda
          </p>

          <div className='flex w-full flex-col space-y-3'>
            {items.map(item => (
              <div
                key={item.id}
                className='flex w-full items-center justify-between gap-4'
              >
                <div className='flex items-center gap-3'>
                  <Icon
                    icon='mdi:pin'
                    className='shrink-0 text-[22px] text-[#d32f2f]'
                  />
                  <div className='flex flex-col'>
                    <span className='text-sm font-semibold leading-[1.3] text-zinc-900'>
                      {item.city}
                    </span>
                    <span className='text-xs leading-[1.3] text-zinc-500'>
                      {item.mobile_phone_text || item.mobile_phone}
                    </span>
                  </div>
                </div>

                <button
                  type='button'
                  onClick={() => handleBranchClick(item)}
                  className='btn_whatsapp shrink-0 cursor-pointer rounded-lg bg-[#54D62C] px-4 py-1.5 text-white shadow-sm transition-colors hover:bg-[#229A16]'
                >
                  <span className='btn_whatsapp pointer-events-none flex items-center gap-2'>
                    <Icon
                      icon='dashicons:whatsapp'
                      className='btn_whatsapp pointer-events-none text-[18px] text-white'
                    />
                    <span className='btn_whatsapp pointer-events-none text-sm font-semibold text-white'>
                      Chat Whatsapp
                    </span>
                  </span>
                </button>
              </div>
            ))}
          </div>
        </div>

        <div className='mt-6 flex justify-end pt-2'>
          <button
            type='button'
            onClick={onClose}
            className='inline-flex cursor-pointer items-center gap-1.5 rounded-lg border border-zinc-300 bg-white px-3 py-1.5 text-sm font-semibold text-zinc-700 transition-colors hover:bg-zinc-100'
          >
            <Icon icon='eva:arrow-ios-back-fill' className='text-[18px]' />
            <span>Close</span>
          </button>
        </div>
      </div>
    </div>
  )
}
