// src/components/rtmp-status-viewer.tsx
"use client";

import { useState, useEffect } from 'react';
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/components/ui/table";
import { Badge } from '@/components/ui/badge';
import { Skeleton } from '@/components/ui/skeleton';

interface RtmpStream {
  name: string;
  time: number; // Uptime in ms
  bw_in: number; // Bandwidth in bytes/sec
  bytes_in: number;
  bw_audio: number;
  bw_video: number;
  client: {
    address: string;
    time: number;
    flashver: string;
    dropped: number;
  };
  meta: {
    video: {
      width: number;
      height: number;
      frame_rate: number;
      codec: string;
    };
    audio: {
      codec: string;
      profile: string;
      channels: number;
      sample_rate: number;
    };
  };
}

interface RtmpStatusViewerProps {
    fetchUrl?: string;
}

const formatUptime = (ms: number) => {
  if (ms < 0) return '00:00:00';
  const totalSeconds = Math.floor(ms / 1000);
  const hours = Math.floor(totalSeconds / 3600).toString().padStart(2, '0');
  const minutes = Math.floor((totalSeconds % 3600) / 60).toString().padStart(2, '0');
  const seconds = (totalSeconds % 60).toString().padStart(2, '0');
  return `${hours}:${minutes}:${seconds}`;
};

const formatBitrate = (bytesPerSecond: number) => {
  if (bytesPerSecond === 0) return '0 kbps';
  const kbps = (bytesPerSecond * 8) / 1000;
  return `${kbps.toFixed(0)} kbps`;
};

export function RtmpStatusViewer({ fetchUrl = '/api/rtmp-stat' }: RtmpStatusViewerProps) {
  const [streams, setStreams] = useState<RtmpStream[]>([]);
  const [isLoading, setIsLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);

  useEffect(() => {
    const fetchStats = async () => {
      try {
        // Use a proxy for external URLs to avoid CORS issues in the browser
        const urlToFetch = fetchUrl.startsWith('http') ? `/api/rtmp-stat?url=${encodeURIComponent(fetchUrl)}` : fetchUrl;
        const response = await fetch(urlToFetch);
        
        if (!response.ok) {
          throw new Error(`Failed to fetch stats: ${response.statusText} (status: ${response.status})`);
        }
        const xmlText = await response.text();
        
        const parser = new DOMParser();
        const xmlDoc = parser.parseFromString(xmlText, "application/xml");
        
        const errorNode = xmlDoc.querySelector('parsererror');
        if (errorNode) {
            throw new Error("Failed to parse XML from stats endpoint.");
        }

        const streamNodes = xmlDoc.querySelectorAll('stream');
        const parsedStreams: RtmpStream[] = Array.from(streamNodes).map(node => {
          const get = (tag: string, parent: Element | null = node) => parent?.querySelector(tag)?.textContent || '';
          const getNum = (tag: string, parent: Element | null = node) => Number(get(tag, parent));

          const metaNode = node.querySelector('meta');
          const videoNode = metaNode?.querySelector('video');
          const audioNode = metaNode?.querySelector('audio');
          const clientNode = node.querySelector('client');
          
          return {
            name: get('name'),
            time: getNum('time'),
            bw_in: getNum('bw_in'),
            bytes_in: getNum('bytes_in'),
            bw_audio: getNum('bw_audio'),
            bw_video: getNum('bw_video'),
            client: {
              address: get('address', clientNode),
              time: getNum('time', clientNode),
              flashver: get('flashver', clientNode),
              dropped: getNum('dropped', clientNode),
            },
            meta: {
              video: {
                width: getNum('width', videoNode),
                height: getNum('height', videoNode),
                frame_rate: getNum('frame_rate', videoNode),
                codec: get('codec', videoNode),
              },
              audio: {
                codec: get('codec', audioNode),
                profile: get('profile', audioNode),
                channels: getNum('channels', audioNode),
                sample_rate: getNum('sample_rate', audioNode),
              },
            },
          };
        });

        setStreams(parsedStreams);
        setError(null);
      } catch (err: any) {
        console.error("Error fetching or parsing RTMP stats:", err);
        setError(err.message || 'Could not connect to the statistics server.');
        setStreams([]); // Clear streams on error
      } finally {
        setIsLoading(false);
      }
    };

    fetchStats();
    const interval = setInterval(fetchStats, 5000); // Poll every 5 seconds

    return () => clearInterval(interval);
  }, [fetchUrl]);

  if (isLoading) {
    return (
      <div className="space-y-2">
        <Skeleton className="h-8 w-full" />
        <Skeleton className="h-8 w-full" />
        <Skeleton className="h-8 w-full" />
      </div>
    );
  }

  if (error) {
    return <p className="text-destructive text-center py-4">{error}</p>
  }

  if (streams.length === 0) {
    return <p className="text-muted-foreground text-center py-4">No active RTMP streams.</p>;
  }


  return (
    <Table>
      <TableHeader>
        <TableRow>
          <TableHead>Stream Key</TableHead>
          <TableHead>Uptime</TableHead>
          <TableHead>Bitrate</TableHead>
          <TableHead>Resolution</TableHead>
          <TableHead>Client</TableHead>
        </TableRow>
      </TableHeader>
      <TableBody>
        {streams.map((stream) => (
          <TableRow key={stream.name}>
            <TableCell className="font-medium">
              <Badge variant="secondary">{stream.name}</Badge>
            </TableCell>
            <TableCell>{formatUptime(stream.time)}</TableCell>
            <TableCell>{formatBitrate(stream.bw_in)}</TableCell>
            <TableCell>
              {stream.meta.video.width > 0 ? `${stream.meta.video.width}x${stream.meta.video.height}@${stream.meta.video.frame_rate}fps` : 'N/A'}
            </TableCell>
            <TableCell>
                <div className="text-xs">
                    <p>IP: {stream.client.address}</p>
                    <p>Agent: {stream.client.flashver}</p>
                </div>
            </TableCell>
          </TableRow>
        ))}
      </TableBody>
    </Table>
  );
}
