'use client';

import { useEffect, useState } from 'react';
import { getVideoUrl, getMediaUrl, VideoUrlData } from '@/services/strapi';
import Backdrop from './Backdrop';

export default function VideoBackground() {
  const [videoData, setVideoData] = useState<VideoUrlData | null>(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);

  useEffect(() => {
    async function fetchVideo() {
      try {
        setLoading(true);
        const data = await getVideoUrl();
        setVideoData(data);
        
        if (!data) {
          setError('No video data found');
        }
      } catch (err) {
        setError(err instanceof Error ? err.message : 'Failed to fetch video');
      } finally {
        setLoading(false);
      }
    }

    fetchVideo();
  }, []);

  if (loading) {
    return (
      <div className="fixed inset-0 flex items-center justify-center bg-black">
        <p className="text-white text-lg">Loading...</p>
      </div>
    );
  }

  if (error) {
    return (
      <div className="fixed inset-0 flex items-center justify-center bg-black">
        <div className="text-center p-8">
          <p className="text-red-400 text-lg mb-2">Error: {error}</p>
          <p className="text-xs text-gray-400">
            Make sure Strapi is running and the NEXT_PUBLIC_STRAPI_TOKEN is set correctly
          </p>
        </div>
      </div>
    );
  }

  if (!videoData || !videoData.background) {
    return (
      <div className="fixed inset-0 flex items-center justify-center bg-black">
        <p className="text-yellow-400 text-lg">No video background found in Strapi</p>
      </div>
    );
  }

  const mediaUrl = getMediaUrl(videoData.background);

  if (!mediaUrl) {
    return (
      <div className="fixed inset-0 flex items-center justify-center bg-black">
        <p className="text-yellow-400 text-lg">Invalid media URL</p>
      </div>
    );
  }

  return (
    <>
      <div className="fixed inset-0 w-screen h-screen overflow-hidden">
        {videoData.background.mime.startsWith('video/') ? (
          <video
            src={mediaUrl}
            autoPlay
            loop
            muted
            playsInline
            className="w-full h-full object-cover"
          >
            Your browser does not support the video tag.
          </video>
        ) : videoData.background.mime.startsWith('image/') ? (
          <img
            src={mediaUrl}
            alt={videoData.background.alternativeText || 'Background'}
            className="w-full h-full object-cover"
          />
        ) : (
          <div className="fixed inset-0 flex items-center justify-center bg-black">
            <p className="text-white">Unsupported media type</p>
          </div>
        )}
      </div>
      <Backdrop />
    </>
  );
}

