"use client";

import { useState, useEffect, useRef } from "react";
import type { Stream, UploadedVideo } from "@/types";
import { Button } from "@/components/ui/button";
import { Card, CardContent, CardDescription, CardFooter, CardHeader, CardTitle } from "@/components/ui/card";
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/components/ui/table";
import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogHeader,
  DialogTitle,
  DialogFooter,
  DialogClose,
} from "@/components/ui/dialog";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { Textarea } from "@/components/ui/textarea";
import { RadioGroup, RadioGroupItem } from "@/components/ui/radio-group";
import { ArrowLeft, Edit, UserCog, Send, Eye, Users, LogOut, PlusCircle, UploadCloud, Link as LinkIcon, Film, Play as PlayIcon, Video as VideoIconLucide, Briefcase } from "lucide-react";
import Link from "next/link";
import { useToast } from "@/hooks/use-toast";
import { HlsPlayer } from "@/components/stream-player";
import { useAuth } from "@/contexts/AuthContext";
import { useRouter } from "next/navigation";
import { db } from "@/lib/firebase";
import { ref, onValue, get, update, push, set, serverTimestamp, query, orderByChild, equalTo } from "firebase/database";


const MAX_VIDEO_DURATION_SECONDS = 180; 
const MAX_VIDEO_FILE_SIZE_MB = 20;

export default function UserDashboardPage() {
  const [isClient, setIsClient] = useState(false);
  const [isLoading, setIsLoading] = useState(true);
  const [editableStreams, setEditableStreams] = useState<Stream[]>([]);
  const [editingStream, setEditingStream] = useState<Stream | null>(null);
  const [isEditDialogOpen, setIsEditDialogOpen] = useState(false);
  const { toast } = useToast();

  const [editedName, setEditedName] = useState('');
  const [editedUrl1, setEditedUrl1] = useState('');
  const [editedUrl2, setEditedUrl2] = useState('');
  const [editedUrl3, setEditedUrl3] = useState('');
  const [editedDescription, setEditedDescription] = useState('');

  const [selectedStreamForPreview, setSelectedStreamForPreview] = useState<Stream | null>(null);
  const [isPreviewDialogOpen, setIsPreviewDialogOpen] = useState(false);
  const [activePreviewPlayingUrl, setActivePreviewPlayingUrl] = useState<string | null>(null);

  const [newStreamName, setNewStreamName] = useState('');
  const [newStreamUrl1, setNewStreamUrl1] = useState('');
  const [newStreamUrl2, setNewStreamUrl2] = useState('');
  const [newStreamUrl3, setNewStreamUrl3] = useState('');
  const [newStreamDescription, setNewStreamDescription] = useState('');
  const [lastSubmittedStreamForPreview, setLastSubmittedStreamForPreview] = useState<Stream | null>(null);
  const [isPreviewSubmittedStreamDialogOpen, setIsPreviewSubmittedStreamDialogOpen] = useState(false);

  const [videoSubmissionType, setVideoSubmissionType] = useState<'upload' | 'url'>('upload');
  const [videoFile, setVideoFile] = useState<File | null>(null);
  const [videoUrl, setVideoUrl] = useState('');
  const [videoTitle, setVideoTitle] = useState('');
  const [videoDescription, setVideoDescription] = useState('');
  const [videoPreviewSrc, setVideoPreviewSrc] = useState<string | null>(null);
  const videoFileRef = useRef<HTMLInputElement>(null);
  const [videoDuration, setVideoDuration] = useState<number | null>(null);

  const [approvedUserVideos, setApprovedUserVideos] = useState<UploadedVideo[]>([]);
  const [selectedVideoToPlay, setSelectedVideoToPlay] = useState<UploadedVideo | null>(null);
  const [isPlayVideoDialogOpen, setIsPlayVideoDialogOpen] = useState(false);

  const { isAuthenticated, userRole, logout, userId } = useAuth();
  const router = useRouter();

  const loadCreatorDataFromRTDB = async () => {
    if (!userId) return;
    setIsLoading(true);
    try {
      // Use onValue for real-time updates on streams
      const streamsQuery = query(ref(db, 'streams'), orderByChild('creatorId'), equalTo(userId));
      onValue(streamsQuery, (snapshot) => {
        const streamsData = snapshot.val() || {};
        const userStreams: Stream[] = Object.keys(streamsData)
          .map(key => ({ id: key, ...streamsData[key] }))
          .filter(s => s.status === 'approved'); // Only show editable approved streams
        
        setEditableStreams(userStreams.sort((a,b) => (b.createdAt || 0) - (a.createdAt || 0)));
      });

      // Use get() for videos as we don't need real-time updates for the approved list here
      const videosQuery = query(ref(db, 'videos'), orderByChild('creatorId'), equalTo(userId));
      const videosSnapshot = await get(videosQuery);
      const videosData = videosSnapshot.val() || {};
      const userVideos: UploadedVideo[] = Object.keys(videosData)
        .map(key => ({ id: key, ...videosData[key] }))
        .filter(v => v.status === 'approved');

      setApprovedUserVideos(userVideos.sort((a,b) => (b.actionedAt || 0) - (a.actionedAt || 0)));

    } catch (error) {
      console.error("Error fetching creator data from Realtime Database:", error);
      toast({
        title: "Error",
        description: "Could not load your dashboard data.",
        variant: "destructive",
      });
    } finally {
      setIsLoading(false);
    }
  };

  useEffect(() => {
    setIsClient(true);
    if (typeof window !== 'undefined') {
      if (!isAuthenticated || (userRole !== 'creator' && userRole !== 'admin') || !userId) {
        router.push('/login');
        return;
      }
      loadCreatorDataFromRTDB();
    }
  // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [isAuthenticated, userRole, router, userId]);

  const handleEditStream = (streamToEdit: Stream) => {
    setEditingStream(streamToEdit);
    setEditedName(streamToEdit.name);
    setEditedUrl1(streamToEdit.sourceUrls[0] || '');
    setEditedUrl2(streamToEdit.sourceUrls[1] || '');
    setEditedUrl3(streamToEdit.sourceUrls[2] || '');
    setEditedDescription(streamToEdit.description || '');
    setIsEditDialogOpen(true);
  };

  const validateUrlForForm = (url: string, fieldName: string, isPrimary = false) => {
    if (isPrimary && !url.trim()) {
        toast({ title: "Validation Error", description: `${fieldName} is required.`, variant: "destructive" });
        return false;
    }
    if (url.trim() && (!url.startsWith('http://') && !url.startsWith('https://'))) {
        toast({ title: "Validation Error", description: `URL for "${fieldName}" must start with http:// or https://.`, variant: "destructive" });
        return false;
    }
    if (url.trim() && !url.endsWith('.m3u8')) {
        toast({ title: "Validation Error", description: `URL for "${fieldName}" must end with .m3u8.`, variant: "destructive" });
        return false;
    }
    return true;
  };

  const handleSaveStream = async () => {
    if (!editingStream || !userId) return;
    if (editingStream.creatorId !== userId) {
        toast({ title: "Error", description: "You cannot edit a stream you do not own.", variant: "destructive" });
        return;
    }
    if (!validateUrlForForm(editedUrl1, "Primary HLS URL", true) || (editedUrl2.trim() && !validateUrlForForm(editedUrl2, "Backup HLS URL 1")) || (editedUrl3.trim() && !validateUrlForForm(editedUrl3, "Backup HLS URL 2"))) return;

    const updatedSourceUrls = [editedUrl1.trim()];
    if (editedUrl2.trim()) updatedSourceUrls.push(editedUrl2.trim());
    if (editedUrl3.trim()) updatedSourceUrls.push(editedUrl3.trim());

    try {
        const streamRef = ref(db, `streams/${editingStream.id}`);
        await update(streamRef, {
            name: editedName.trim() || editingStream.name,
            sourceUrls: updatedSourceUrls,
            description: editedDescription.trim() || '',
        });

        toast({ title: "Stream Updated", description: `${editingStream.name} has been updated.` });
        setIsEditDialogOpen(false);
        setEditingStream(null);
        // Data will update via onValue listener
    } catch (error) {
        console.error("Error updating stream in Realtime Database:", error);
        toast({ title: "Error", description: "Could not update the stream.", variant: "destructive" });
    }
  };

  const handleRequestStreamDeletion = async (streamToDelete: Stream) => {
    if (streamToDelete.creatorId !== userId) {
        toast({ title: "Error", description: "You can only request deletion for your own streams.", variant: "destructive" });
        return;
    }

    try {
        const streamRef = ref(db, `streams/${streamToDelete.id}`);
        await update(streamRef, { status: 'pending_deletion' });
        
        toast({ title: "Deletion Requested", description: `Request to delete ${streamToDelete.name} sent to admin.` });
        // Data will update via onValue listener
    } catch (error) {
        console.error("Error requesting stream deletion:", error);
        toast({ title: "Error", description: "Could not request deletion.", variant: "destructive" });
    }
  };

  const handleAddNewStreamSubmit = async () => {
    if (!newStreamName.trim()) {
      toast({ title: "Validation Error", description: "Stream Name is required.", variant: "destructive" });
      return;
    }
    if (!validateUrlForForm(newStreamUrl1, "Primary HLS URL", true) || (newStreamUrl2.trim() && !validateUrlForForm(newStreamUrl2, "Backup HLS URL 1")) || (newStreamUrl3.trim() && !validateUrlForForm(newStreamUrl3, "Backup HLS URL 2"))) return;
    if (!userId) {
      toast({ title: "Authentication Error", description: "You must be logged in.", variant: "destructive" });
      return;
    }
    
    const sourceUrls = [newStreamUrl1.trim()];
    if (newStreamUrl2.trim()) sourceUrls.push(newStreamUrl2.trim());
    if (newStreamUrl3.trim()) sourceUrls.push(newStreamUrl3.trim());

    const newStreamData: Omit<Stream, 'id'> = {
      name: newStreamName.trim(), 
      sourceUrls,
      description: newStreamDescription.trim() || '',
      views: 0, 
      creatorId: userId,
      status: 'pending',
      createdAt: serverTimestamp() as any, // RTDB server timestamp object
    };

    try {
        const newStreamRef = push(ref(db, 'streams'));
        await set(newStreamRef, newStreamData);
        toast({ title: "Stream Submitted", description: `${newStreamData.name} submitted for approval.` });
        
        setLastSubmittedStreamForPreview({ ...newStreamData, id: newStreamRef.key!, createdAt: Date.now() });
        setIsPreviewSubmittedStreamDialogOpen(true);

        // Reset form
        setNewStreamName(''); setNewStreamUrl1(''); setNewStreamUrl2(''); setNewStreamUrl3(''); setNewStreamDescription('');
    } catch (error) {
        console.error("Error submitting new stream:", error);
        toast({ title: "Submission Failed", description: "Could not submit your stream to the database.", variant: "destructive" });
    }
  };

  const handleVideoFileChange = (event: React.ChangeEvent<HTMLInputElement>) => {
    const file = event.target.files?.[0];
    setVideoUrl(''); 
    setVideoDuration(null);
    setVideoPreviewSrc(null); 

    if (file) {
      if (file.size > MAX_VIDEO_FILE_SIZE_MB * 1024 * 1024) {
        toast({ title: "File Too Large", description: `Video file size cannot exceed ${MAX_VIDEO_FILE_SIZE_MB}MB for this prototype. Consider using the URL option for larger files.`, variant: "destructive", duration: 7000 });
        setVideoFile(null);
        if(videoFileRef.current) videoFileRef.current.value = "";
        return;
      }

      setVideoFile(file);
      const reader = new FileReader();
      reader.onloadend = () => {
        setVideoPreviewSrc(reader.result as string); // For client-side preview only
        const videoElement = document.createElement('video');
        videoElement.src = reader.result as string;
        videoElement.onloadedmetadata = () => {
          setVideoDuration(videoElement.duration);
          if (videoElement.duration > MAX_VIDEO_DURATION_SECONDS) {
            toast({ title: "Video Too Long", description: `Video duration (${Math.round(videoElement.duration)}s) exceeds ${MAX_VIDEO_DURATION_SECONDS / 60} minutes.`, variant: "destructive" });
          }
        };
        videoElement.onerror = () => {
            toast({title: "Preview Error", description: "Could not load video preview. The file might be corrupted or in an unsupported format.", variant: "destructive"});
            setVideoPreviewSrc(null);
            setVideoDuration(null);
            setVideoFile(null);
            if(videoFileRef.current) videoFileRef.current.value = "";
        }
      };
      reader.readAsDataURL(file);
    } else {
      setVideoFile(null);
    }
  };

  const handleVideoUrlChange = (event: React.ChangeEvent<HTMLInputElement>) => {
    const url = event.target.value;
    setVideoUrl(url);
    setVideoFile(null); 
    setVideoDuration(0); 
    setVideoPreviewSrc(null); 
    if (videoFileRef.current) videoFileRef.current.value = ""; 

    if (url.trim().startsWith('http://') || url.trim().startsWith('https://')) {
      setVideoPreviewSrc(url.trim());
    }
  };

  const handleVideoSubmit = async () => {
    if (!videoTitle.trim() || !userId) {
      toast({ title: "Missing Information", description: "Video title is required.", variant: "destructive" });
      return;
    }

    let newVideoData: Omit<UploadedVideo, 'id'> | null = null;

    if (videoSubmissionType === 'upload' && videoFile) {
      if (videoDuration === null) { 
        toast({ title: "Processing Error", description: "Video duration not yet determined. Please wait or re-select file.", variant: "destructive" });
        return;
      }
      if (videoDuration > MAX_VIDEO_DURATION_SECONDS) {
        toast({ title: "Video Too Long", description: `Video duration (${Math.round(videoDuration)}s) exceeds ${MAX_VIDEO_DURATION_SECONDS / 60} minutes.`, variant: "destructive" });
        return;
      }
      
      newVideoData = {
        creatorId: userId,
        title: videoTitle.trim(),
        description: videoDescription.trim() || '',
        fileName: videoFile.name,
        fileType: videoFile.type,
        duration: videoDuration, 
        submittedAt: new Date().toISOString(),
        status: 'pending',
        createdAt: serverTimestamp() as any,
      };
    } else if (videoSubmissionType === 'url' && videoUrl.trim()) {
      if (!videoUrl.trim().startsWith('http://') && !videoUrl.trim().startsWith('https://')) {
        toast({ title: "Invalid URL", description: "Video URL must start with http:// or https://.", variant: "destructive" });
        return;
      }
      newVideoData = {
        creatorId: userId,
        title: videoTitle.trim(),
        description: videoDescription.trim() || '',
        videoStorageUrl: videoUrl.trim(),
        duration: 0, 
        fileName: "URL Submission", 
        fileType: "N/A", 
        submittedAt: new Date().toISOString(),
        status: 'pending',
        createdAt: serverTimestamp() as any,
      };
    } else {
        toast({ title: "Missing Information", description: "Please provide a video file or a valid video URL.", variant: "destructive" });
        return;
    }

    if (newVideoData) {
        try {
            const newVideoRef = push(ref(db, 'videos'));
            await set(newVideoRef, newVideoData);
            toast({ title: "Video Submitted", description: `${newVideoData.title} has been submitted for approval.` });
            setVideoFile(null); setVideoUrl(''); setVideoTitle(''); setVideoDescription(''); setVideoPreviewSrc(null); setVideoDuration(null);
            if(videoFileRef.current) videoFileRef.current.value = "";
        } catch (error) {
            console.error("Error submitting new video:", error);
            toast({ title: "Submission Failed", description: "Could not submit your video to the database.", variant: "destructive" });
        }
    }
  };

  const openPreviewDialog = (stream: Stream) => {
    setSelectedStreamForPreview(stream);
    setActivePreviewPlayingUrl(null);
    setIsPreviewDialogOpen(true);
  };

  const closePreviewDialog = () => {
    setIsPreviewDialogOpen(false);
    setSelectedStreamForPreview(null);
    setActivePreviewPlayingUrl(null);
  };

  const openPlayVideoDialog = (video: UploadedVideo) => {
    setSelectedVideoToPlay(video);
    setIsPlayVideoDialogOpen(true);
  };
  const closePlayVideoDialog = () => {
    setIsPlayVideoDialogOpen(false);
    setSelectedVideoToPlay(null);
  };

  if (!isClient || !isAuthenticated || (userRole !== 'creator' && userRole !== 'admin') || !userId) {
    return (
      <div className="min-h-screen flex flex-col items-center justify-center p-4">
        <Card className="w-full max-w-2xl shadow-xl rounded-lg">
          <CardHeader><CardTitle className="text-2xl text-center">Access Denied</CardTitle></CardHeader>
          <CardContent><p className="text-muted-foreground text-center">Redirecting to login...</p></CardContent>
        </Card>
      </div>
    );
  }
  
  if (isLoading) {
    return (
      <div className="min-h-screen flex flex-col items-center justify-center p-4">
        <Card className="w-full max-w-2xl shadow-xl rounded-lg">
          <CardHeader><CardTitle className="text-2xl text-center">Loading Dashboard...</CardTitle></CardHeader>
          <CardContent><p className="text-muted-foreground text-center">Fetching your data from the cloud...</p></CardContent>
        </Card>
      </div>
    );
  }

  return (
    <main className="min-h-screen flex flex-col items-center p-4 sm:p-6 md:p-8">
      <div className="w-full max-w-4xl space-y-8">
        <Card className="shadow-xl rounded-lg">
          <CardHeader className="flex flex-row items-center justify-between">
            <div className="flex items-center gap-2">
              <UserCog className="w-8 h-8 text-primary" />
              <CardTitle className="text-3xl font-bold text-foreground">Creator Dashboard</CardTitle>
            </div>
            <div className="flex items-center gap-2">
                <Button variant="outline" asChild><Link href="/" className="flex items-center gap-2"><ArrowLeft className="w-4 h-4" />Home</Link></Button>
                <Button variant="outline" asChild><Link href="/invest" className="flex items-center gap-2"><Briefcase className="w-4 h-4" />Invest</Link></Button>
                <Button variant="ghost" onClick={logout} className="text-destructive-foreground hover:bg-destructive/10"><LogOut className="w-4 h-4 mr-2" />Logout</Button>
            </div>
          </CardHeader>
        </Card>

        <Card>
          <CardHeader>
            <CardTitle className="text-2xl text-foreground">Manage Your HLS Streams</CardTitle>
            <CardDescription>Edit, preview, or request deletion for your HLS streams.</CardDescription>
          </CardHeader>
          <CardContent>
            {editableStreams.length === 0 ? (
              <p className="text-muted-foreground">No HLS streams submitted or approved yet for your account.</p>
            ) : (
              <Table>
                <TableHeader><TableRow><TableHead>Name</TableHead><TableHead>Description</TableHead><TableHead className="text-center">Views</TableHead><TableHead className="text-right">Actions</TableHead></TableRow></TableHeader>
                <TableBody>
                  {editableStreams.map((stream) => (
                    <TableRow key={stream.id}>
                      <TableCell className="font-medium">{stream.name}</TableCell>
                      <TableCell className="text-sm text-muted-foreground max-w-xs truncate">{stream.description || "N/A"}</TableCell>
                      <TableCell className="text-center text-sm text-muted-foreground"><div className="flex items-center justify-center gap-1"><Users className="w-4 h-4" />{(stream.views || 0).toLocaleString()}</div></TableCell>
                      <TableCell className="text-right space-x-2">
                        <Button variant="outline" size="sm" onClick={() => openPreviewDialog(stream)}><Eye className="w-4 h-4 mr-1" />Preview</Button>
                        <Button variant="outline" size="sm" onClick={() => handleEditStream(stream)}><Edit className="w-4 h-4 mr-1" />Edit</Button>
                        <Button variant="ghost" size="sm" className="text-yellow-500 hover:text-yellow-600 hover:bg-yellow-500/10" onClick={() => handleRequestStreamDeletion(stream)}><Send className="w-4 h-4 mr-1" />Request Deletion</Button>
                      </TableCell>
                    </TableRow>
                  ))}
                </TableBody>
              </Table>
            )}
          </CardContent>
        </Card>

        <Card className="shadow-md border border-border">
            <CardHeader><CardTitle className="text-xl flex items-center gap-2 text-foreground"><PlusCircle className="w-6 h-6 text-accent" />Add New HLS Stream (for Admin Approval)</CardTitle><CardDescription className="text-muted-foreground">Submitted HLS streams require admin approval.</CardDescription></CardHeader>
            <CardContent className="space-y-4">
                <div><Label htmlFor="new-stream-name-creator">Stream Name</Label><Input id="new-stream-name-creator" value={newStreamName} onChange={(e) => setNewStreamName(e.target.value)} placeholder="E.g., My Live Event" /></div>
                <div><Label htmlFor="new-stream-url1-creator">Primary HLS URL (.m3u8)</Label><Input id="new-stream-url1-creator" type="url" value={newStreamUrl1} onChange={(e) => setNewStreamUrl1(e.target.value)} placeholder="https://example.com/stream1.m3u8" /></div>
                <div><Label htmlFor="new-stream-url2-creator">Backup HLS URL 1 (Optional)</Label><Input id="new-stream-url2-creator" type="url" value={newStreamUrl2} onChange={(e) => setNewStreamUrl2(e.target.value)} placeholder="https://backup.com/stream2.m3u8" /></div>
                <div><Label htmlFor="new-stream-url3-creator">Backup HLS URL 2 (Optional)</Label><Input id="new-stream-url3-creator" type="url" value={newStreamUrl3} onChange={(e) => setNewStreamUrl3(e.target.value)} placeholder="https://another.com/stream3.m3u8" /></div>
                <div><Label htmlFor="new-stream-description-creator">Description (Optional)</Label><Textarea id="new-stream-description-creator" value={newStreamDescription} onChange={(e) => setNewStreamDescription(e.target.value)} placeholder="Brief description." rows={2} /></div>
                <Button onClick={handleAddNewStreamSubmit} className="w-full sm:w-auto bg-accent text-accent-foreground hover:bg-accent/90"><PlusCircle className="mr-2 h-4 w-4" /> Submit Stream</Button>
            </CardContent>
        </Card>

        {/* Your Approved Videos Section */}
        <Card>
          <CardHeader>
            <CardTitle className="text-2xl text-foreground flex items-center gap-2"><VideoIconLucide className="w-6 h-6 text-primary" />Your Approved Videos</CardTitle>
            <CardDescription>Videos you uploaded that have been approved by an admin.</CardDescription>
          </CardHeader>
          <CardContent>
            {approvedUserVideos.length === 0 ? (
              <p className="text-muted-foreground">No videos approved yet for your account.</p>
            ) : (
              <Table>
                <TableHeader>
                  <TableRow>
                    <TableHead>Title</TableHead>
                    <TableHead>Description</TableHead>
                    <TableHead>Source</TableHead>
                    <TableHead>Approved At</TableHead>
                    <TableHead className="text-right">Actions</TableHead>
                  </TableRow>
                </TableHeader>
                <TableBody>
                  {approvedUserVideos.map((video) => (
                    <TableRow key={video.id}>
                      <TableCell className="font-medium">{video.title}</TableCell>
                      <TableCell className="text-sm text-muted-foreground max-w-xs truncate">{video.description || "N/A"}</TableCell>
                       <TableCell className="text-xs text-muted-foreground truncate">
                        {video.videoStorageUrl ? 'URL' : video.fileName || 'Uploaded File'}
                      </TableCell>
                      <TableCell className="text-xs text-muted-foreground">{video.actionedAt ? new Date(video.actionedAt).toLocaleString() : "N/A"}</TableCell>
                      <TableCell className="text-right">
                        <Button variant="outline" size="sm" onClick={() => openPlayVideoDialog(video)}>
                          <PlayIcon className="w-4 h-4 mr-1" />Play
                        </Button>
                      </TableCell>
                    </TableRow>
                  ))}
                </TableBody>
              </Table>
            )}
          </CardContent>
        </Card>

        {/* Video Submission Section */}
        <Card className="shadow-md border border-border">
          <CardHeader>
            <CardTitle className="text-xl flex items-center gap-2 text-foreground">
              <Film className="w-6 h-6 text-accent" />
              Submit Short Video (Max 3 mins)
            </CardTitle>
            <CardDescription className="text-muted-foreground">
              Upload a short video clip (max {MAX_VIDEO_FILE_SIZE_MB}MB) or provide a URL. Videos require admin approval.
            </CardDescription>
          </CardHeader>
          <CardContent className="space-y-4">
            <div>
              <Label htmlFor="video-title-creator" className="text-sm font-medium">Video Title</Label>
              <Input id="video-title-creator" value={videoTitle} onChange={(e) => setVideoTitle(e.target.value)} placeholder="E.g., My Awesome Clip" className="mt-1"/>
            </div>

            <RadioGroup defaultValue="upload" onValueChange={(value: 'upload' | 'url') => { setVideoSubmissionType(value); setVideoPreviewSrc(null); setVideoFile(null); setVideoUrl(''); if (videoFileRef.current) videoFileRef.current.value = ""; }} className="flex space-x-4">
              <div className="flex items-center space-x-2">
                <RadioGroupItem value="upload" id="video-upload-option" />
                <Label htmlFor="video-upload-option" className="flex items-center gap-1"><UploadCloud className="w-4 h-4" />Upload File</Label>
              </div>
              <div className="flex items-center space-x-2">
                <RadioGroupItem value="url" id="video-url-option" />
                <Label htmlFor="video-url-option" className="flex items-center gap-1"><LinkIcon className="w-4 h-4" />Provide URL</Label>
              </div>
            </RadioGroup>

            {videoSubmissionType === 'upload' && (
              <div>
                <Label htmlFor="video-file-creator" className="text-sm font-medium">Video File</Label>
                <Input id="video-file-creator" type="file" accept="video/mp4,video/webm,video/ogg" onChange={handleVideoFileChange} className="mt-1" ref={videoFileRef} />
                {videoDuration !== null && videoFile && (
                  <p className={`text-xs mt-1 ${videoDuration > MAX_VIDEO_DURATION_SECONDS ? 'text-destructive' : 'text-muted-foreground'}`}>
                    Duration: {Math.floor(videoDuration / 60)}m {Math.round(videoDuration % 60)}s
                    {videoDuration > MAX_VIDEO_DURATION_SECONDS && " (Too long!)"}
                  </p>
                )}
              </div>
            )}

            {videoSubmissionType === 'url' && (
              <div>
                <Label htmlFor="video-url-creator" className="text-sm font-medium">Video URL</Label>
                <Input id="video-url-creator" type="url" value={videoUrl} onChange={handleVideoUrlChange} placeholder="https://example.com/myvideo.mp4" className="mt-1"/>
              </div>
            )}
            
            {(videoPreviewSrc) && (
              <div className="space-y-2">
                <Label className="text-sm font-medium">Preview</Label>
                <video src={videoPreviewSrc} controls className="w-full max-h-60 rounded-md border bg-muted object-contain" key={videoPreviewSrc}></video>
              </div>
            )}

            <div>
              <Label htmlFor="video-description-creator" className="text-sm font-medium">Description (Optional)</Label>
              <Textarea id="video-description-creator" value={videoDescription} onChange={(e) => setVideoDescription(e.target.value)} placeholder="A brief description of the video content." className="mt-1" rows={2}/>
            </div>
            <Button 
              onClick={handleVideoSubmit} 
              className="w-full sm:w-auto bg-accent text-accent-foreground hover:bg-accent/90" 
              disabled={
                !videoTitle.trim() ||
                (videoSubmissionType === 'upload' && (!videoFile || (videoDuration !== null && videoDuration > MAX_VIDEO_DURATION_SECONDS) || (videoFile && videoFile.size > MAX_VIDEO_FILE_SIZE_MB * 1024 * 1024) )) ||
                (videoSubmissionType === 'url' && (!videoUrl.trim() || (!videoUrl.startsWith('http://') && !videoUrl.startsWith('https://')) ))
              }
            >
              <UploadCloud className="mr-2 h-4 w-4" /> Submit Video for Approval
            </Button>
            {videoSubmissionType === 'upload' && !videoFile && <p className="text-xs text-muted-foreground">Select a video file to enable submission.</p>}
             {videoSubmissionType === 'upload' && videoFile && videoFile.size > MAX_VIDEO_FILE_SIZE_MB * 1024 * 1024 && <p className="text-xs text-destructive">Video file is too large (max {MAX_VIDEO_FILE_SIZE_MB}MB).</p>}
            {videoSubmissionType === 'upload' && videoFile && videoDuration !== null && videoDuration > MAX_VIDEO_DURATION_SECONDS && <p className="text-xs text-destructive">Video is too long to be submitted.</p>}
            {videoSubmissionType === 'url' && !videoUrl.trim() && <p className="text-xs text-muted-foreground">Enter a video URL to enable submission.</p>}
            {videoSubmissionType === 'url' && videoUrl.trim() && (!videoUrl.startsWith('http://') && !videoUrl.startsWith('https://')) && <p className="text-xs text-destructive">Video URL must start with http:// or https://.</p>}

          </CardContent>
        </Card>

      </div>

      {/* Edit Stream Dialog */}
      {editingStream && (
        <Dialog open={isEditDialogOpen} onOpenChange={(isOpen) => { if (!isOpen) setEditingStream(null); setIsEditDialogOpen(isOpen); }}>
          <DialogContent className="sm:max-w-[600px]">
            <DialogHeader><DialogTitle>Edit Stream: {editingStream.name}</DialogTitle><DialogDescription>Update stream details.</DialogDescription></DialogHeader>
            <div className="grid gap-4 py-4">
              <div className="grid grid-cols-4 items-center gap-4"><Label htmlFor="edit-stream-name" className="text-right col-span-1">Name</Label><Input id="edit-stream-name" value={editedName} onChange={(e) => setEditedName(e.target.value)} className="col-span-3" /></div>
              <div className="grid grid-cols-4 items-center gap-4"><Label htmlFor="edit-stream-url1" className="text-right col-span-1">Primary URL</Label><Input id="edit-stream-url1" type="url" value={editedUrl1} onChange={(e) => setEditedUrl1(e.target.value)} className="col-span-3" /></div>
              <div className="grid grid-cols-4 items-center gap-4"><Label htmlFor="edit-stream-url2" className="text-right col-span-1">Backup URL 1</Label><Input id="edit-stream-url2" type="url" value={editedUrl2} onChange={(e) => setEditedUrl2(e.target.value)} className="col-span-3" /></div>
              <div className="grid grid-cols-4 items-center gap-4"><Label htmlFor="edit-stream-url3" className="text-right col-span-1">Backup URL 2</Label><Input id="edit-stream-url3" type="url" value={editedUrl3} onChange={(e) => setEditedUrl3(e.target.value)} className="col-span-3" /></div>
              <div className="grid grid-cols-4 items-center gap-4"><Label htmlFor="edit-stream-description" className="text-right col-span-1">Description</Label><Textarea id="edit-stream-description" value={editedDescription} onChange={(e) => setEditedDescription(e.target.value)} className="col-span-3" /></div>
            </div>
            <DialogFooter><DialogClose asChild><Button type="button" variant="outline">Cancel</Button></DialogClose><Button type="button" onClick={handleSaveStream}>Save Changes</Button></DialogFooter>
          </DialogContent>
        </Dialog>
      )}

      {selectedStreamForPreview && (
        <Dialog open={isPreviewDialogOpen} onOpenChange={(isOpen) => { setIsPreviewDialogOpen(isOpen); if (!isOpen) closePreviewDialog(); }}>
          <DialogContent className="sm:max-w-[600px] md:max-w-[800px] lg:max-w-[1000px] w-full">
            <DialogHeader><DialogTitle>Preview HLS: {selectedStreamForPreview.name}</DialogTitle>{selectedStreamForPreview.description && (<DialogDescription>{selectedStreamForPreview.description}</DialogDescription>)}</DialogHeader>
            <div className="my-4 rounded-lg overflow-hidden"><HlsPlayer src={selectedStreamForPreview.sourceUrls} autoPlay={true} onActiveSourceChanged={setActivePreviewPlayingUrl}/></div>
            {activePreviewPlayingUrl && (<div className="mt-2 text-sm"><span className="font-medium">Active Source: </span><code className="text-xs bg-muted p-1 rounded-sm break-all">{activePreviewPlayingUrl}</code></div>)}
            <DialogFooter className="mt-4"><Button type="button" variant="secondary" onClick={closePreviewDialog}>Close</Button></DialogFooter>
          </DialogContent>
        </Dialog>
      )}

      {lastSubmittedStreamForPreview && (
        <Dialog open={isPreviewSubmittedStreamDialogOpen} onOpenChange={setIsPreviewSubmittedStreamDialogOpen}>
          <DialogContent className="sm:max-w-[600px] md:max-w-[800px] lg:max-w-[1000px] w-full">
            <DialogHeader><DialogTitle>Preview HLS: {lastSubmittedStreamForPreview.name}</DialogTitle>{lastSubmittedStreamForPreview.description && (<DialogDescription>{lastSubmittedStreamForPreview.description}</DialogDescription>)}<DialogDescription className="text-xs pt-1">Submitted for admin approval.</DialogDescription></DialogHeader>
            <div className="my-4 rounded-lg overflow-hidden"><HlsPlayer src={lastSubmittedStreamForPreview.sourceUrls} autoPlay={true} /></div>
            <DialogFooter><Button type="button" variant="secondary" onClick={() => setIsPreviewSubmittedStreamDialogOpen(false)}>Close</Button></DialogFooter>
          </DialogContent>
        </Dialog>
      )}

      {/* Play Uploaded Video Dialog */}
      {selectedVideoToPlay && (
        <Dialog open={isPlayVideoDialogOpen} onOpenChange={(isOpen) => { if (!isOpen) closePlayVideoDialog(); }}>
          <DialogContent className="sm:max-w-[600px] md:max-w-[800px] lg:max-w-[1000px] w-full">
            <DialogHeader>
              <DialogTitle>Playing: {selectedVideoToPlay.title}</DialogTitle>
              {selectedVideoToPlay.description && <DialogDescription>{selectedVideoToPlay.description}</DialogDescription>}
            </DialogHeader>
            <div className="my-4 rounded-lg overflow-hidden">
              {selectedVideoToPlay.videoStorageUrl ? (
                <video 
                  src={selectedVideoToPlay.videoStorageUrl} 
                  controls 
                  autoPlay 
                  className="w-full aspect-video rounded-md bg-muted object-contain" 
                />
              ) : ( 
                <div className="aspect-video w-full flex flex-col items-center justify-center bg-muted rounded-md p-4">
                  <VideoIconLucide className="w-16 h-16 text-muted-foreground mb-2"/>
                  <p className="text-muted-foreground text-center">Video preview not available.</p>
                  <p className="text-xs text-muted-foreground text-center mt-1">This video was likely a direct file upload and cannot be previewed here due to storage limitations of the prototype.</p>
                </div>
              )}
            </div>
            <DialogFooter className="mt-4">
              <Button type="button" variant="secondary" onClick={closePlayVideoDialog}>Close Player</Button>
            </DialogFooter>
          </DialogContent>
        </Dialog>
      )}
    </main>
  );
}