import { useEffect } from "react";
import { useQuery } from "@tanstack/react-query";
import { Session, Transcription } from "@shared/schema";
import { useParams } from "wouter";
import { useLanguage } from "@/hooks/use-language";
import { useAuth } from "@/hooks/use-auth";
import { Loader2 } from "lucide-react";
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs";
import { Card } from "@/components/ui/card";


const LiveStreamContent = ({
  session,
  transcriptions,
  t,
}: {
  session: Session;
  transcriptions: Transcription[] | undefined;
  t: any;
}) => {
  console.log('Session data:', session);
  const embedUrl = session.liveStreamUrl;

  return (
    <div className="container mx-auto p-6 space-y-8">
      <div className="text-center">
        <h1 className="text-3xl font-bold">{session.sessionTitle}</h1>
        <p className="text-muted-foreground" dir="rtl">
          {session.sessionTitleAr}
        </p>
      </div>

      {/* Vimeo Event Stream - Using iframe */}
      <div
        className="relative w-full overflow-hidden bg-muted rounded-lg"
        style={{ paddingTop: "56.25%" }}
      >
        {embedUrl ? (
          <iframe
            src={embedUrl}
            frameBorder="0"
            allow="autoplay; fullscreen; picture-in-picture"
            allowFullScreen
            style={{
              position: "absolute",
              top: 0,
              left: 0,
              width: "100%",
              height: "100%",
            }}
          ></iframe>
        ) : (
          <p className="text-center text-red-500">Invalid Vimeo URL</p>
        )}
      </div>

      {/* Transcriptions */}
      <Tabs defaultValue="en" className="w-full">
        <TabsList className="grid w-full grid-cols-2">
          <TabsTrigger value="en">
            {t("English Transcription", "النص الإنجليزي")}
          </TabsTrigger>
          <TabsTrigger value="ar">
            {t("Arabic Transcription", "النص العربي")}
          </TabsTrigger>
        </TabsList>
        <TabsContent value="en">
          <Card className="p-4 space-y-4 max-h-[300px] overflow-y-auto">
            {transcriptions
              ?.sort(
                (a, b) =>
                  new Date(b.createdAt).getTime() -
                  new Date(a.createdAt).getTime(),
              )
              .map((transcription) => (
                <div
                  key={transcription.id}
                  className="border-b last:border-0 pb-2 last:pb-0"
                >
                  <p>{transcription.translatedText}</p>
                  <time className="text-xs text-muted-foreground">
                    {new Date(transcription.createdAt).toLocaleTimeString()}
                  </time>
                </div>
              ))}
          </Card>
        </TabsContent>
        <TabsContent value="ar">
          <Card className="p-4 space-y-4 max-h-[300px] overflow-y-auto">
            {transcriptions
              ?.sort(
                (a, b) =>
                  new Date(b.createdAt).getTime() -
                  new Date(a.createdAt).getTime(),
              )
              .map((transcription) => (
                <div
                  key={transcription.id}
                  className="border-b last:border-0 pb-2 last:pb-0"
                >
                  <p dir="rtl">{transcription.originalText}</p>
                  <time className="text-xs text-muted-foreground">
                    {new Date(transcription.createdAt).toLocaleTimeString()}
                  </time>
                </div>
              ))}
          </Card>
        </TabsContent>
      </Tabs>
    </div>
  );
};

export default function LiveStreamSinglePage() {
  const { id } = useParams<{ id: string }>();
  const { t } = useLanguage();
  const { user } = useAuth();

  // Query session details - Updated to fetch single session
  const { data: session, isLoading: loadingSession } = useQuery<Session>({
    queryKey: [`/api/sessions/${id}`],
    enabled: !!id,
  });

  // Query approved transcriptions 
  const { data: transcriptions } = useQuery<Transcription[]>({
    queryKey: ["/api/transcriptions"],
    select: (transcriptions) =>
      transcriptions?.filter(
        (t) => t.sessionId === Number(id) && t.status === "accepted",
      ),
    refetchInterval: 5000, 
  });

  if (loadingSession) {
    return (
      <div className="flex justify-center items-center min-h-screen">
        <Loader2 className="h-8 w-8 animate-spin" />
      </div>
    );
  }

  if (!session) {
    return (
      <div className="flex flex-col items-center justify-center min-h-screen space-y-4">
        <h2 className="text-2xl font-bold">
          {t("Session Not Found", "الجلسة غير موجودة")}
        </h2>
      </div>
    );
  }

  return (
    <LiveStreamContent
      session={session}
      transcriptions={transcriptions}
      t={t}
    />
  );
}