'use client';

import React, { useState, useEffect, forwardRef } from 'react';
import { Loader2 } from 'lucide-react';
import { DefaultService } from '@lib/api';

interface SecureVideoProps extends React.VideoHTMLAttributes<HTMLVideoElement> {
    src?: string;
}

export const SecureVideo = forwardRef<HTMLVideoElement, SecureVideoProps>(({ src, className, style, crossOrigin, ...props }, ref) => {
    const [blobUrl, setBlobUrl] = useState<string | null>(null);
    const [isFallback, setIsFallback] = useState(false);

    useEffect(() => {
        if (!src) return;
        if (src.startsWith('data:') || src.startsWith('blob:')) {
            setBlobUrl(src);
            setIsFallback(false);
            return;
        }

        let active = true;
        let createdUrl: string | null = null;

        const fetchAndCreateBlob = async () => {
             const tryFetch = async (u: string) => {
                 try {
                     const res = await fetch(u, { mode: 'cors' });
                     if (!res.ok) return null;
                     return await res.blob();
                 } catch (e) {
                     return null;
                 }
             };

             let blob = await tryFetch(src);
             let finalSignedUrl: string | null = null;
             
             // If direct fetch fails, try signing
             if (!blob) {
                 try {
                     const response = await DefaultService.signUrlEndpoint({ url: src });
                     const signedUrl = (response as any).data.url;
                     if (signedUrl && signedUrl !== src) {
                        finalSignedUrl = signedUrl;
                        blob = await tryFetch(signedUrl);
                     }
                 } catch (e) {
                     // ignore
                 }
             }

             if (active) {
                if (blob) {
                     // Use original type if available, otherwise fallback to mp4
                    const type = blob.type || 'video/mp4';
                    const videoBlob = new Blob([blob], { type });
                    const url = URL.createObjectURL(videoBlob);
                    createdUrl = url;
                    setBlobUrl(url);
                    setIsFallback(false);
                } else {
                    console.warn("SecureVideo blob fetch failed, falling back to direct URL (signed if available)");
                    setBlobUrl(finalSignedUrl || src);
                    setIsFallback(true);
                }
             }
        };
        
        fetchAndCreateBlob();

        return () => {
            active = false;
            if (createdUrl) {
                URL.revokeObjectURL(createdUrl);
            }
        };
    }, [src]);

    if (!blobUrl) return <div className={`flex items-center justify-center bg-card ${className}`}><Loader2 className="animate-spin text-muted-foreground" /></div>;

    return (
        <video 
            ref={ref}
            src={blobUrl} 
            className={className}
            playsInline
            style={{ backgroundColor: '#18181b', ...style }}
            crossOrigin={isFallback ? undefined : crossOrigin}
            {...props}
        />
    );
});

SecureVideo.displayName = 'SecureVideo';
