import { useEffect, useState } from "react";
import { useLanguage } from "@/hooks/use-language";
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { Button } from "@/components/ui/button";
import { Switch } from "@/components/ui/switch";
import { Alert, AlertDescription } from "@/components/ui/alert";
import { Power, AlertCircle, Save, Lock } from "lucide-react";
import { useQuery, useMutation } from "@tanstack/react-query";
import { apiRequest, queryClient } from "@/lib/queryClient";
import { useAuth } from "@/hooks/use-auth";
import { useRoleCheck } from "@/hooks/use-role-check";
import { useLocation } from "wouter";
import type { Session, Event, Transcription } from "@shared/schema";
import ReactPlayer from "react-player";

interface RTMPStatus {
  isRunning: boolean;
  error?: string;
}

interface ActiveTranscriptionStatus {
  activeSessionIds: number[];
}

export default function TranscriptionsPage() {
  const { t } = useLanguage();
  const { user } = useAuth();
  const { isAdminOrModerator } = useRoleCheck();
  const [, setLocation] = useLocation();

  // If user is not an admin or moderator, show access denied
  if (!isAdminOrModerator()) {
    return (
      <div className="flex flex-col items-center justify-center min-h-screen space-y-4">
        <Lock className="h-12 w-12 text-muted-foreground" />
        <Alert variant="destructive" className="max-w-lg">
          <AlertDescription>
            {t(
              "Access Denied. Only administrators and moderators can access this page.",
              "تم رفض الوصول. يمكن للمسؤولين والمشرفين فقط الوصول إلى هذه الصفحة."
            )}
          </AlertDescription>
        </Alert>
        <Button variant="link" onClick={() => setLocation("/")}>
          {t("Return to Home", "العودة إلى الصفحة الرئيسية")}
        </Button>
      </div>
    );
  }

  const [selectedEventId, setSelectedEventId] = useState<number | null>(null);
  const [selectedSessionId, setSelectedSessionId] = useState<number | null>(null);
  const [transcriptionStatus, setTranscriptionStatus] = useState<string>("");
  const [error, setError] = useState<string | null>(null);
  const [isLiveMode, setIsLiveMode] = useState(false);

  // Query events
  const { data: events } = useQuery<Event[]>({
    queryKey: ["/api/events"],
  });

  // Query sessions based on selected event
  const { data: sessions } = useQuery<Session[]>({
    queryKey: ["/api/sessions", selectedEventId],
    enabled: !!selectedEventId,
  });

  // Query active transcription sessions
  const { data: activeTranscriptions } = useQuery<ActiveTranscriptionStatus>({
    queryKey: ["/api/transcriptions/active"],
    refetchInterval: 5000,
  });

  // Check if current session is transcribing
  const isTranscribing = activeTranscriptions?.activeSessionIds?.includes(selectedSessionId ?? -1) ?? false;

  // Update transcriptions query to filter by sessionId
  const { data: transcriptions } = useQuery<Transcription[]>({
    queryKey: ["/api/transcriptions", selectedSessionId],
    enabled: !!selectedSessionId,
    refetchInterval: 5000,
  });

  // RTMP server status
  const { data: rtmpStatus } = useQuery<RTMPStatus>({
    queryKey: ["/api/rtmp/status"],
    enabled: !!selectedSessionId,
    refetchInterval: 5000,
  });

  // Reset states when session changes
  useEffect(() => {
    setTranscriptionStatus("");
    setError(null);
  }, [selectedSessionId]);

  // Start transcription mutation
  const startTranscriptionMutation = useMutation({
    mutationFn: async () => {
      setError(null);

      if (isLiveMode && !rtmpStatus?.isRunning) {
        throw new Error("RTMP link is not receiving transmission");
      }

      const res = await apiRequest("POST", "/api/transcriptions/start", {
        sessionId: selectedSessionId,
        mode: isLiveMode ? "live" : "test",
      });

      if (!res.ok) {
        const errorData = await res.json();
        throw new Error(errorData.error || "Failed to start transcription");
      }

      return res.json();
    },
    onSuccess: () => {
      setTranscriptionStatus("✅ Transcription started successfully");
      queryClient.invalidateQueries({ queryKey: ["/api/transcriptions/active"] });
      queryClient.invalidateQueries({ queryKey: ["/api/transcriptions", selectedSessionId] });
    },
    onError: (error: Error) => {
      setTranscriptionStatus(""); // Clear the "starting" status
      setError(error.message);
    },
  });

  // Stop transcription mutation
  const stopTranscriptionMutation = useMutation({
    mutationFn: async () => {
      if (!selectedSessionId) return;
      const res = await apiRequest("POST", "/api/transcriptions/stop", {
        sessionId: selectedSessionId,
      });
      if (!res.ok) {
        const errorData = await res.json();
        throw new Error(errorData.error || "Failed to stop transcription");
      }
      return res.json();
    },
    onSuccess: () => {
      setTranscriptionStatus("");
      setError(null);
      queryClient.invalidateQueries({ queryKey: ["/api/transcriptions/active"] });
      queryClient.invalidateQueries({ queryKey: ["/api/transcriptions", selectedSessionId] });
    },
    onError: (error: Error) => {
      setError(error.message);
    },
  });

  // Update transcription mutation
  const updateTranscriptionMutation = useMutation({
    mutationFn: async ({ id, status }: { id: number; status: string }) => {
      const res = await apiRequest("POST", `/api/transcriptions/${id}/status`, { status });
      return res.json();
    },
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ["/api/transcriptions", selectedSessionId] });
    },
  });

  // Add mutation for saving edits
  const saveEditsMutation = useMutation({
    mutationFn: async (data: { id: number; originalText: string; translatedText: string }) => {
      const res = await apiRequest("POST", `/api/transcriptions/${data.id}/edit`, data);
      if (!res.ok) {
        throw new Error("Failed to update transcription");
      }
      return res.json();
    },
    onSuccess: () => {
      setEditingTranscription(null); // Reset editing state
      queryClient.invalidateQueries({ queryKey: ["/api/transcriptions", selectedSessionId] });
    },
    onError: (error: Error) => {
      console.error("Failed to save edits:", error);
    },
  });

  // Add editing state
  const [editingTranscription, setEditingTranscription] = useState<{
    id: number;
    originalText: string;
    translatedText: string;
  } | null>(null);


  // Update the transcription card content to support editing
  function renderTranscriptionCard(transcription: Transcription) {
    const isEditing = editingTranscription?.id === transcription.id;

    return (
      <Card key={transcription.id}>
        <CardHeader>
          <CardTitle>
            {t("Transcription", "النسخ")} #{transcription.id}
            <span className="text-sm text-muted-foreground ml-2">
              {new Date(transcription.createdAt).toLocaleString()}
            </span>
          </CardTitle>
        </CardHeader>
        <CardContent className="space-y-4">
          <div className="grid grid-cols-2 gap-4">
            <div className="space-y-2">
              <h4 className="font-medium">{t("Original Text", "النص الأصلي")}</h4>
              <textarea
                className="w-full min-h-[100px] p-2 border rounded"
                value={isEditing ? editingTranscription?.originalText : transcription.originalText}
                onChange={(e) =>
                  isEditing &&
                  setEditingTranscription({
                    ...editingTranscription!,
                    originalText: e.target.value,
                  })
                }
                readOnly={!isEditing}
              />
              <p className="text-sm text-muted-foreground">
                {t("Source Language", "لغة المصدر")}: {transcription.sourceLanguage}
              </p>
            </div>
            <div className="space-y-2">
              <h4 className="font-medium">{t("Translated Text", "النص المترجم")}</h4>
              <textarea
                className="w-full min-h-[100px] p-2 border rounded"
                value={isEditing ? editingTranscription?.translatedText : transcription.translatedText}
                onChange={(e) =>
                  isEditing &&
                  setEditingTranscription({
                    ...editingTranscription!,
                    translatedText: e.target.value,
                  })
                }
                readOnly={!isEditing}
              />
            </div>
          </div>
          <div className="flex justify-end gap-2">
            {isEditing ? (
              <>
                <Button variant="outline" onClick={() => setEditingTranscription(null)}>
                  {t("Cancel", "إلغاء")}
                </Button>
                <Button
                  variant="default"
                  onClick={() => saveEditsMutation.mutate(editingTranscription!)}
                  disabled={saveEditsMutation.isPending}
                >
                  <Save className="w-4 h-4 mr-2" />
                  {t("Save", "حفظ")}
                </Button>
              </>
            ) : (
              <>
                <Button
                  variant="outline"
                  onClick={() =>
                    setEditingTranscription({
                      id: transcription.id,
                      originalText: transcription.originalText,
                      translatedText: transcription.translatedText,
                    })
                  }
                >
                  {t("Edit", "تعديل")}
                </Button>
                <Button
                  variant="default"
                  onClick={() => {
                    updateTranscriptionMutation.mutate({
                      id: transcription.id,
                      status: "accepted",
                    });
                  }}
                >
                  {t("Accept", "قبول")}
                </Button>
                <Button
                  variant="destructive"
                  onClick={() => {
                    updateTranscriptionMutation.mutate({
                      id: transcription.id,
                      status: "rejected",
                    });
                  }}
                >
                  {t("Reject", "رفض")}
                </Button>
              </>
            )}
          </div>
        </CardContent>
      </Card>
    );
  }

  const startServerMutation = useMutation({
    mutationFn: async () => {
      const res = await apiRequest("POST", "/api/rtmp/start");
      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("Transcription Management", "إدارة النسخ")}
        </h1>
      </div>

      <Card>
        <CardHeader>
          <CardTitle>{t("Session Selection", "اختيار الجلسة")}</CardTitle>
        </CardHeader>
        <CardContent className="space-y-4">
          <div className="grid grid-cols-2 gap-4">
            <div>
              <label className="text-sm font-medium mb-2 block">
                {t("Select Event", "اختر الفعالية")}
              </label>
              <select
                className="w-full border rounded p-2"
                value={selectedEventId || ""}
                onChange={(e) => {
                  const value = e.target.value;
                  setSelectedEventId(value ? Number(value) : null);
                  setSelectedSessionId(null);
                }}
              >
                <option value="">{t("Select...", "اختر...")}</option>
                {events?.map((event) => (
                  <option key={event.id} value={event.id}>
                    {event.eventName}
                  </option>
                ))}
              </select>
            </div>
            <div>
              <label className="text-sm font-medium mb-2 block">
                {t("Select Session", "اختر الجلسة")}
              </label>
              <select
                className="w-full border rounded p-2"
                value={selectedSessionId || ""}
                onChange={(e) => {
                  const value = e.target.value;
                  setSelectedSessionId(value ? Number(value) : null);
                }}
                disabled={!selectedEventId}
              >
                <option value="">{t("Select...", "اختر...")}</option>
                {sessions?.map((session) => {
                  const isActive = activeTranscriptions?.activeSessionIds.includes(session.id);
                  return (
                    <option key={session.id} value={session.id}>
                      {session.sessionTitle} {isActive ? "🎙" : ""}
                    </option>
                  );
                })}
              </select>
            </div>
          </div>

          {selectedSessionId && (
            <div className="space-y-4">
              <div className="flex items-center justify-between">
                <div className="space-y-1">
                  <p className="text-sm font-medium">
                    {t("RTMP Stream URL", "عنوان بث RTMP")}
                  </p>
                  <code className="bg-muted px-2 py-1 rounded text-sm">
                    rtmp://{window.location.hostname}/live/session_{selectedSessionId}
                  </code>
                </div>
                <div className="flex items-center gap-2">
                  <div
                    className={`w-3 h-3 rounded-full ${
                      rtmpStatus?.isRunning ? "bg-green-500" : "bg-red-500"
                    }`}
                  />
                  {!rtmpStatus?.isRunning && (
                    <Button onClick={() => startServerMutation.mutate()} disabled={startServerMutation.isPending}>
                      <Power className="mr-2 h-4 w-4" />
                      {t("Start Stream Server", "بدء خادم البث")}
                    </Button>
                  )}
                </div>
              </div>

              {rtmpStatus?.error && (
                <Alert variant="destructive">
                  <AlertCircle className="h-4 w-4" />
                  <AlertDescription>{rtmpStatus.error}</AlertDescription>
                </Alert>
              )}

              <div className="space-y-2">
                <div className="flex items-center gap-4">
                  <Button
                    onClick={() => {
                      if (isTranscribing) {
                        stopTranscriptionMutation.mutate();
                      } else {
                        startTranscriptionMutation.mutate();
                      }
                    }}
                    disabled={!selectedSessionId || (isLiveMode && !rtmpStatus?.isRunning)}
                  >
                    {isTranscribing
                      ? t("Stop Transcription", "إيقاف النسخ")
                      : t("Start Transcription", "بدء النسخ")}
                  </Button>
                  <div className="flex items-center gap-2">
                    <Switch
                      checked={isLiveMode}
                      onCheckedChange={setIsLiveMode}
                      disabled={isTranscribing}
                    />
                    <span className="text-sm">
                      {isLiveMode ? t("Live Mode", "وضع المباشر") : t("Test Mode", "وضع الاختبار")}
                    </span>
                  </div>
                  {/* Add ReactPlayer for RTMP stream monitoring */}
                  {selectedSessionId && isLiveMode && (
                    <div className="w-64 aspect-video bg-muted rounded overflow-hidden">
                      <ReactPlayer
                        url={`rtmp://confapp.co:1935/live/session_${selectedSessionId}`}
                        playing
                        muted={false}
                        controls
                        width="100%"
                        height="100%"
                        config={{
                          file: {
                            attributes: {
                              crossOrigin: "anonymous"
                            }
                          }
                        }}
                      />
                    </div>
                  )}
                </div>
                {error && (
                  <Alert variant="destructive">
                    <AlertCircle className="h-4 w-4" />
                    <AlertDescription>{error}</AlertDescription>
                  </Alert>
                )}
                {transcriptionStatus && !error && (
                  <p className="text-sm text-muted-foreground">{transcriptionStatus}</p>
                )}
              </div>
            </div>
          )}
        </CardContent>
      </Card>

      {selectedSessionId && (
        <Tabs defaultValue="pending" className="space-y-4">
          <TabsList>
            <TabsTrigger value="pending">
              {t("Pending", "قيد الانتظار")}
            </TabsTrigger>
            <TabsTrigger value="accepted">
              {t("Accepted", "مقبول")}
            </TabsTrigger>
            <TabsTrigger value="rejected">
              {t("Rejected", "مرفوض")}
            </TabsTrigger>
          </TabsList>

          <TabsContent value="pending" className="space-y-4">
            {transcriptions
              ?.filter((t) => t.status === "pending" && t.sessionId === selectedSessionId)
              .map(renderTranscriptionCard)}
          </TabsContent>

          <TabsContent value="accepted" className="space-y-4">
            {transcriptions
              ?.filter((t) => t.status === "accepted" && t.sessionId === selectedSessionId)
              .map(renderTranscriptionCard)}
          </TabsContent>

          <TabsContent value="rejected" className="space-y-4">
            {transcriptions
              ?.filter((t) => t.status === "rejected" && t.sessionId === selectedSessionId)
              .map(renderTranscriptionCard)}
          </TabsContent>
        </Tabs>
      )}
    </div>
  );
}