'use client'

import { useEffect, useRef } from 'react'

interface GrafanaPanelProps {
  dashboardUID: string
  panelId: number
  from?: string
  to?: string
  refresh?: string
  theme?: 'light' | 'dark'
  height?: string
  width?: string
}

export default function GrafanaPanel({
  dashboardUID,
  panelId,
  from = 'now-6h',
  to = 'now',
  refresh = '30s',
  theme = 'dark',
  height = '400px',
  width = '100%',
}: GrafanaPanelProps) {
  const iframeRef = useRef<HTMLIFrameElement>(null)
  const grafanaURL = process.env.NEXT_PUBLIC_GRAFANA_URL || 'http://localhost:3001'

  useEffect(() => {
    if (iframeRef.current) {
      const url = new URL(`${grafanaURL}/d/${dashboardUID}`)
      url.searchParams.set('orgId', '1')
      url.searchParams.set('from', from)
      url.searchParams.set('to', to)
      url.searchParams.set('refresh', refresh)
      url.searchParams.set('theme', theme)
      url.searchParams.set('panelId', panelId.toString())
      url.searchParams.set('kiosk', 'tv')

      iframeRef.current.src = url.toString()
    }
  }, [dashboardUID, panelId, from, to, refresh, theme, grafanaURL])

  return (
    <div className="w-full rounded-lg overflow-hidden border border-gray-700">
      <iframe
        ref={iframeRef}
        width={width}
        height={height}
        frameBorder="0"
        className="bg-gray-900"
        title={`Grafana Panel ${panelId}`}
      />
    </div>
  )
}

