'use client'

import { useEffect, useState } from 'react'
import { resolveBrowserAppUrl } from '@/lib/appUrls'
import { useStorefrontPreferences } from './StorefrontShell'

export type FrameId = 'sign-in'

const frameConfig: Record<FrameId, { label: string; appUrl: string; path: string }> = {
  'sign-in': {
    label: 'Sign in',
    appUrl: process.env.NEXT_PUBLIC_DASHBOARD_URL ?? 'http://localhost:3000/dashboard',
    path: '/dashboard/sign-in',
  },
}

export function getDefaultFramePath(target: FrameId) {
  if (typeof window === 'undefined') {
    return frameConfig[target].path
  }

  return frameConfig[target].path
}

export function buildFrameUrl(appUrl: string, path: string) {
  if (typeof window === 'undefined') return path

  const resolvedAppUrl = resolveBrowserAppUrl(appUrl)
  const appBase = new URL(resolvedAppUrl, window.location.origin)
  const target = new URL(path, window.location.origin)
  appBase.pathname = target.pathname
  appBase.search = target.search
  appBase.hash = ''
  return appBase.toString()
}

export const FRAME_HEIGHT = 'calc(100vh - 56px)'

export default function WorkspaceFrame({ target }: { target: FrameId }) {
  const { language, theme } = useStorefrontPreferences()
  const [src, setSrc] = useState('')
  const [framePath, setFramePath] = useState(() => getDefaultFramePath(target))
  const config = frameConfig[target]
  const loadingLabel = {
    en: 'Loading',
    fr: 'Chargement',
    ar: 'جارٍ تحميل',
  }[language]

  useEffect(() => {
    setFramePath(getDefaultFramePath(target))
  }, [target])

  useEffect(() => {
    function handleFrameMessage(event: MessageEvent) {
      if (!event.data || typeof event.data !== 'object') return

      const message = event.data as { type?: string; path?: string }

      if (target === 'sign-in' && message.type === 'rentaldrivego:employee-login' && typeof message.path === 'string') {
        window.location.replace(message.path)
        return
      }

      if ((message.type === 'rentaldrivego:embedded-path' || message.type === 'rentaldrivego:employee-login') && typeof message.path === 'string') {
        setFramePath(message.path)
      }
    }

    window.addEventListener('message', handleFrameMessage)
    return () => window.removeEventListener('message', handleFrameMessage)
  }, [target])

  useEffect(() => {
    if (target === 'sign-in' && src) return

    const nextUrl = new URL(buildFrameUrl(config.appUrl, framePath))
    nextUrl.searchParams.set('theme', theme)
    nextUrl.searchParams.set('lang', language)
    nextUrl.searchParams.set('embedded', '1')
    setSrc(nextUrl.toString())
  }, [config.appUrl, framePath, language, src, target, theme])

  const content = src ? (
    <iframe
      title={config.label}
      src={src}
      className="block w-full border-0 bg-white dark:bg-blue-950"
      style={{ height: FRAME_HEIGHT }}
    />
  ) : (
    <div
      className="flex items-center justify-center text-sm text-stone-500 dark:text-stone-300"
      style={{ height: FRAME_HEIGHT }}
    >
      {loadingLabel} {config.label}…
    </div>
  )

  if (target === 'sign-in') {
    return <main className="min-h-[calc(100vh-56px)]">{content}</main>
  }

  return (
    <main className="site-page">
      <div className="site-section py-6 sm:py-8 lg:py-10">
        <section className="site-panel overflow-hidden p-0">{content}</section>
      </div>
    </main>
  )
}
