import { useEffect, useState } from "react";
import ReactPlayer from "react-player";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { Alert, AlertDescription } from "@/components/ui/alert";
import { useLanguage } from "@/hooks/use-language";
import { Button } from "@/components/ui/button";
import { Loader2, Power } from "lucide-react";
import { useQuery, useMutation } from "@tanstack/react-query";
import { apiRequest, queryClient } from "@/lib/queryClient";
import { useAuth } from "@/hooks/use-auth";

export default function StreamTestPage() {
  const { t } = useLanguage();
  const { user } = useAuth();
  const [isPlaying, setIsPlaying] = useState(false);
  const [streamError, setStreamError] = useState<string | null>(null);

  // RTMP Stream Configuration
  const streamKey = "test-stream";
  const rtmpServer = `rtmp://${window.location.hostname}/live`; // Using default RTMP port
  const rtmpUrl = `${rtmpServer}/${streamKey}`;

  // Query RTMP server status
  const { data: rtmpStatus, isLoading: isLoadingStatus } = useQuery({
    queryKey: ["/api/rtmp/status"],
    refetchInterval: 5000, // Poll every 5 seconds
  });

  // Start RTMP server mutation
  const startServerMutation = useMutation({
    mutationFn: async () => {
      const res = await apiRequest("POST", "/api/rtmp/start");
      return res.json();
    },
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ["/api/rtmp/status"] });
    },
  });

  // Stop RTMP server mutation
  const stopServerMutation = useMutation({
    mutationFn: async () => {
      const res = await apiRequest("POST", "/api/rtmp/stop");
      return res.json();
    },
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ["/api/rtmp/status"] });
    },
  });

  return (
    <div className="space-y-8">
      <div className="flex justify-between items-center">
        <h1 className="text-3xl font-bold">
          {t("Stream Test", "اختبار البث")}
        </h1>
        {user?.role === 'admin' && (
          <Button
            variant={rtmpStatus?.isRunning ? "destructive" : "default"}
            onClick={() => {
              if (rtmpStatus?.isRunning) {
                stopServerMutation.mutate();
              } else {
                startServerMutation.mutate();
              }
            }}
            disabled={isLoadingStatus || startServerMutation.isPending || stopServerMutation.isPending}
          >
            {(startServerMutation.isPending || stopServerMutation.isPending) ? (
              <Loader2 className="mr-2 h-4 w-4 animate-spin" />
            ) : (
              <Power className="mr-2 h-4 w-4" />
            )}
            {rtmpStatus?.isRunning ?
              t("Stop RTMP Server", "إيقاف خادم RTMP") :
              t("Start RTMP Server", "تشغيل خادم RTMP")
            }
          </Button>
        )}
      </div>

      <Card>
        <CardHeader>
          <CardTitle>{t("Audio Stream", "البث الصوتي")}</CardTitle>
        </CardHeader>
        <CardContent>
          <div className="aspect-video bg-muted rounded-lg overflow-hidden">
            <ReactPlayer
              url={rtmpUrl}
              playing={isPlaying}
              controls
              width="100%"
              height="100%"
              onError={(e) => {
                console.error("Stream playback error:", e);
                setStreamError(t(
                  "Stream not available. Please make sure streaming software is connected.",
                  "البث غير متوفر. يرجى التأكد من اتصال برنامج البث."
                ));
              }}
              onPlay={() => {
                setIsPlaying(true);
                setStreamError(null);
              }}
              onPause={() => setIsPlaying(false)}
            />
          </div>

          {streamError && (
            <Alert className="mt-4" variant="destructive">
              <AlertDescription>{streamError}</AlertDescription>
            </Alert>
          )}

          <div className="mt-6 space-y-4">
            <h3 className="font-semibold text-lg">
              {t("Streaming Instructions", "تعليمات البث")}
            </h3>
            <div className="space-y-2">
              <Alert className="bg-muted">
                <AlertDescription>
                  {rtmpStatus?.isRunning ? (
                    <span className="text-green-600">
                      {t("RTMP Server is running", "خادم RTMP قيد التشغيل")}
                    </span>
                  ) : (
                    <span className="text-red-600">
                      {t("RTMP Server is stopped", "خادم RTMP متوقف")}
                    </span>
                  )}
                </AlertDescription>
              </Alert>
              <p className="text-muted-foreground">
                {t(
                  "To stream audio, use OBS Studio or similar streaming software with these settings:",
                  "لبث الصوت، استخدم OBS Studio أو برنامج بث مماثل مع هذه الإعدادات:"
                )}
              </p>
              <div className="bg-muted p-4 rounded-md space-y-2">
                <p><strong>{t("Server", "الخادم")}:</strong> {rtmpServer}</p>
                <p><strong>{t("Stream Key", "مفتاح البث")}:</strong> {streamKey}</p>
                <p className="text-sm text-yellow-600">
                  {t("Note: Using default RTMP port 1935",
                     "ملاحظة: استخدام منفذ RTMP الافتراضي 1935")}
                </p>
              </div>
              <p className="text-sm text-muted-foreground">
                {t(
                  "In OBS: Go to Settings > Stream, select 'Custom' as service, and enter the server URL and stream key above.",
                  "في OBS: اذهب إلى الإعدادات > البث، اختر 'مخصص' كخدمة، وأدخل عنوان URL للخادم ومفتاح البث أعلاه."
                )}
              </p>
            </div>
          </div>
        </CardContent>
      </Card>
    </div>
  );
}