import React, { useState, useEffect } from "react";
import { apiFetch } from "@/utils/api";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import {
  BarChart,
  Bar,
  XAxis,
  YAxis,
  Tooltip,
  ResponsiveContainer,
} from "recharts";
import { AlertTriangle, Users, Activity } from "lucide-react";
import { Alert, AlertDescription } from "@/components/ui/alert";
import { format } from "date-fns";
import { processBasicData } from "./RealtimeAnalytics";
import { DashboardStatCardMini, DashboardStatCardMiniSkeleton, TOOLTIP_THEMES } from "@/components/dashboard/shared";
import { Skeleton } from "@/components/ui/skeleton";

// Brighter color for dark glass background
const MINI_BAR_COLOR = "#38bdf8"; // sky-400


const MiniRealtimeAnalytics = () => {
  const [basicData, setBasicData] = useState({
    last30MinUsers: 0,
    last5MinUsers: 0,
    byMinute: [],
    tokenQuota: null,
    lastUpdated: null,
  });

  const [loading, setLoading] = useState(true);
  const [isPaused, setIsPaused] = useState(false);
  const [error, setError] = useState(null);

  useEffect(() => {
    let basicInterval;

    const fetchBasicData = async () => {
      if (isPaused) return;
      try {
        const response = await apiFetch("/api/dashboard-analytics/realtime/basic", {
          credentials: "include",
        });

        if (!response.ok) {
          throw new Error("Failed to fetch basic realtime data");
        }

        const result = await response.json();
        const processed = processBasicData(result.data);
        setBasicData(processed);
        setError(null);
        setLoading(false);
      } catch (error) {
        console.error("Error details:", {
          message: error.message,
          stack: error.stack,
          response: error.response,
        });
        if (error.message === "QUOTA_EXCEEDED") {
          setError("Quota exceeded. Analytics paused until manually resumed.");
          setIsPaused(true);
        } else {
          setError("Failed to fetch analytics data");
        }
      }
    };

    // Initial fetch
    fetchBasicData();

    // Set up interval
    basicInterval = setInterval(fetchBasicData, 30000); // 30 seconds

    return () => {
      clearInterval(basicInterval);
    };
  }, [isPaused]);

  const renderContent = () => {
    if (error) {
      return (
        <Alert variant="destructive" className="mb-4">
          <AlertTriangle className="h-4 w-4" />
          <AlertDescription>{error}</AlertDescription>
        </Alert>
      );
    }

    if (loading && !basicData.byMinute?.length) {
      return (
        <div>
          <div className="grid grid-cols-2 gap-2 mt-1 mb-2">
            <DashboardStatCardMiniSkeleton gradient="sky" />
            <DashboardStatCardMiniSkeleton gradient="sky" />
          </div>

          <Card className="bg-gradient-to-br from-sky-900/70 to-sky-800/50 backdrop-blur-xl border-white/[0.08] ring-1 ring-white/[0.05] shadow-lg shadow-black/20">
            <CardContent className="p-4">
              <div className="h-[216px]">
                <div className="h-full w-full relative">
                  {/* Grid lines */}
                  {[...Array(5)].map((_, i) => (
                    <div
                      key={i}
                      className="absolute w-full h-px bg-sky-300/20"
                      style={{ top: `${(i + 1) * 20}%` }}
                    />
                  ))}
                  {/* Y-axis labels */}
                  <div className="absolute left-0 top-0 bottom-0 w-8 flex flex-col justify-between py-4">
                    {[...Array(5)].map((_, i) => (
                      <Skeleton key={i} className="h-3 w-6 bg-sky-300/20 rounded-sm" />
                    ))}
                  </div>
                  {/* X-axis labels */}
                  <div className="absolute left-8 right-4 bottom-0 flex justify-between">
                    {[...Array(6)].map((_, i) => (
                      <Skeleton key={i} className="h-3 w-8 bg-sky-300/20 rounded-sm" />
                    ))}
                  </div>
                  {/* Bars */}
                  <div className="absolute inset-x-8 bottom-6 top-4 flex items-end justify-between gap-1">
                    {[...Array(24)].map((_, i) => (
                      <div
                        key={i}
                        className="w-2 bg-sky-300/20 rounded-sm"
                        style={{ height: `${Math.random() * 80 + 10}%` }}
                      />
                    ))}
                  </div>
                </div>
              </div>
            </CardContent>
          </Card>
        </div>
      );
    }

    return (
      <div>
        <div className="grid grid-cols-2 gap-2 mt-1 mb-2">
          <DashboardStatCardMini
            title="Last 30 Minutes"
            value={basicData.last30MinUsers}
            subtitle="Active users"
            gradient="sky"
            icon={Users}
            iconBackground="bg-sky-400"
          />
          <DashboardStatCardMini
            title="Last 5 Minutes"
            value={basicData.last5MinUsers}
            subtitle="Active users"
            gradient="sky"
            icon={Activity}
            iconBackground="bg-sky-400"
          />
        </div>

        <Card className="bg-gradient-to-br from-sky-900/70 to-sky-800/50 backdrop-blur-xl border-white/[0.08] ring-1 ring-white/[0.05] shadow-lg shadow-black/20">
          <CardContent className="p-4">
            <div className="h-[216px]">
              <ResponsiveContainer width="100%" height="100%">
                <BarChart
                  data={basicData.byMinute}
                  margin={{ top: 5, right: 5, left: -35, bottom: -10 }}
                >
                  <XAxis
                    dataKey="minute"
                    tickFormatter={(value) => value + "m"}
                    className="text-xs"
                    tick={{ fill: "#e0f2fe" }}
                  />
                  <YAxis 
                    className="text-xs" 
                    tick={{ fill: "#e0f2fe" }}
                  />
                  <Tooltip
                    content={({ active, payload }) => {
                      if (active && payload && payload.length) {
                        const styles = TOOLTIP_THEMES.sky;
                        return (
                          <div className={styles.container}>
                            <p className={styles.header}>
                              {payload[0].payload.timestamp}
                            </p>
                            <div className={styles.content}>
                              <div className={styles.row}>
                                <span className={styles.name}>Active Users</span>
                                <span className={styles.value}>{payload[0].value}</span>
                              </div>
                            </div>
                          </div>
                        );
                      }
                      return null;
                    }}
                  />
                  <Bar dataKey="users" fill={MINI_BAR_COLOR} radius={[2, 2, 0, 0]} />
                </BarChart>
              </ResponsiveContainer>
            </div>
          </CardContent>
        </Card>
      </div>
    );
  };

  return renderContent();
};

export default MiniRealtimeAnalytics; 