"use client"

import { useEffect, useState } from "react"
import Loading from "@/components/common/loading.component"
import ErrorBox from "@/components/common/error-box.component"
import EmptyState from "@/components/common/empty-state.component"
import { useApi, getApiErrorMessage } from "@/lib/services/axios.service"
import { ApiEndpoint } from "@/lib/services/api.service"
import { LiveIndexResponseDto } from "@/lib/dto/live.dto"
import VideoPlayerEmbed from "@/components/video/video-player-embed"


export default function LiveView() {
  const [liveEmbed, setLiveEmbed] = useState<string | null>(null)
  const [isLive, setIsLive] = useState(false)
  const [fetchError, setFetchError] = useState<string | null>(null)

  const [{ loading: fetchLoading }, fetchLive] = useApi<LiveIndexResponseDto>({
    url: ApiEndpoint("live", "get"),
    method: "GET",
  })

  const loadLive = async () => {
    setFetchError(null)
    try {
      const response = await fetchLive()
      const result = response?.body

      if (!result?.ok) {
        setFetchError("خطا در دریافت اطلاعات لایو")
        return
      }

      setIsLive(result.data.live)
      setLiveEmbed(result.data.live_embed)
    } catch (err: any) {
      setFetchError(getApiErrorMessage(err))
    }
  }

  useEffect(() => {
    loadLive()
  }, [])

  return (
    <div className="flex flex-col flex-1 bg-background text-right min-h-0 overflow-hidden">
      <div className="flex-1 overflow-y-auto min-h-0 px-2 py-3">

        <Loading loading={fetchLoading}>
          <ErrorBox
            active={!!fetchError}
            title="خطا در بارگذاری"
            description={fetchError}
            showRetry
            onRetry={loadLive}
          >

            <div className="w-full max-w-md mx-auto pb-2 flex flex-col [&>*:not(:last-child)]:mb-1">
              {!isLive ? (
                <EmptyState
                  title="پخش زنده برقرار نیست"
                  description="در حال حاضر هیچ رویداد زنده‌ای در حال پخش نمی‌باشد. لطفاً بعداً مراجعه کنید."
                />
              ) : (
                <VideoPlayerEmbed html={liveEmbed || ""} />
              )}
            </div>

          </ErrorBox>
        </Loading>

      </div>
    </div>
  )
}
