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";

// Helper function to filter transcriptions by status
const filterTranscriptionsByStatus = (
  transcriptions: Transcription[] | undefined,
  status: string,
) => {
  if (!transcriptions) return [];
  const filtered = transcriptions.filter((t) => {
    console.log(`Checking transcription ${t.id}:`, t.status);
    return t.status === status;
  });
  console.log(`Filtered ${status} transcriptions:`, filtered);
  return filtered;
};

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

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

  // 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);

  // 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<{
    activeSessionIds: number[];
  }>({
    queryKey: ["/api/transcriptions/active"],
    refetchInterval: 5000,
  });

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

  // Query transcriptions using our standard apiRequest utility
  const { data: transcriptions } = useQuery<Transcription[]>({
    queryKey: ["/api/sessions", selectedSessionId, "transcriptions"],
    queryFn: async () => {
      if (!selectedSessionId) return [];
      const response = await apiRequest(
        "GET",
        `/api/sessions/${selectedSessionId}/transcriptions`,
      );
      const data = await response.json();
      console.log("Received transcriptions data:", data);

      // Map the transcriptions and ensure status is set
      const mappedTranscriptions = (data.transcriptions || []).map(
        (t: Transcription) => ({
          ...t,
          status: t.status || "pending",
        }),
      );
      console.log("Mapped transcriptions with status:", mappedTranscriptions);
      return mappedTranscriptions;
    },
    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]);

  // Function to format date
  const formatDate = (dateString: string) => {
    try {
      if (!dateString) return "Invalid date";
      const date = new Date(dateString);
      if (isNaN(date.getTime())) {
        throw new Error("Invalid date");
      }
      return date.toLocaleString(undefined, {
        year: "numeric",
        month: "numeric",
        day: "numeric",
        hour: "2-digit",
        minute: "2-digit",
      });
    } catch (error) {
      console.error("Date formatting error:", error);
      return "Invalid date";
    }
  };

  // Update transcription mutation
  const updateTranscriptionMutation = useMutation({
    mutationFn: async ({ id, status }: { id: number; status: string }) => {
      const res = await apiRequest("POST", `/api/transcriptions/${id}/status`, {
        status,
      });
      if (!res.ok) {
        throw new Error("Failed to update transcription status");
      }
      return res.json();
    },
    onSuccess: () => {
      // Invalidate and refetch to get updated data
      queryClient.invalidateQueries({
        queryKey: ["/api/sessions", selectedSessionId, "transcriptions"],
      });
    },
    onError: (error: Error) => {
      console.error("Failed to update transcription status:", error);
    },
  });

  // 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/sessions", selectedSessionId, "transcriptions"],
      });
    },
    onError: (error: Error) => {
      console.error("Failed to save edits:", error);
    },
  });

  // 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/sessions", selectedSessionId, "transcriptions"],
      });
    },
    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/sessions", selectedSessionId, "transcriptions"],
      });
    },
    onError: (error: Error) => {
      setError(error.message);
    },
  });

  // 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"] });
    },
  });

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

  function renderTranscriptionCard(transcription: Transcription) {
    console.log("Rendering 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">
              {formatDate(transcription.createdAt)}
            </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",
                    })
                  }
                  disabled={updateTranscriptionMutation.isPending}
                >
                  {t("Accept", "قبول")}
                </Button>
                <Button
                  variant="destructive"
                  onClick={() =>
                    updateTranscriptionMutation.mutate({
                      id: transcription.id,
                      status: "rejected",
                    })
                  }
                  disabled={updateTranscriptionMutation.isPending}
                >
                  {t("Reject", "رفض")}
                </Button>
              </>
            )}
          </div>
        </CardContent>
      </Card>
    );
  }

  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://transcription.confapp.co/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>
                </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", "قيد الانتظار")} (
              {filterTranscriptionsByStatus(transcriptions, "pending").length})
            </TabsTrigger>
            <TabsTrigger value="accepted">
              {t("Accepted", "مقبول")} (
              {filterTranscriptionsByStatus(transcriptions, "accepted").length})
            </TabsTrigger>
            <TabsTrigger value="rejected">
              {t("Rejected", "مرفوض")} (
              {filterTranscriptionsByStatus(transcriptions, "rejected").length})
            </TabsTrigger>
          </TabsList>

          <TabsContent value="pending" className="space-y-4">
            {filterTranscriptionsByStatus(transcriptions, "pending").map(
              renderTranscriptionCard,
            )}
          </TabsContent>

          <TabsContent value="accepted" className="space-y-4">
            {filterTranscriptionsByStatus(transcriptions, "accepted").map(
              renderTranscriptionCard,
            )}
          </TabsContent>

          <TabsContent value="rejected" className="space-y-4">
            {filterTranscriptionsByStatus(transcriptions, "rejected").map(
              renderTranscriptionCard,
            )}
          </TabsContent>
        </Tabs>
      )}
    </div>
  );
}
