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

const SkeletonCard = ({ colorScheme = "sky" }) => (
  <Card className={`w-full h-[150px] bg-gradient-to-br from-sky-900 to-sky-800 backdrop-blur-sm`}>
    <CardHeader className="flex flex-row items-center justify-between space-y-0 p-4 pb-2">
      <CardTitle>
        <div className="space-y-2">
          <Skeleton className={`h-4 w-24 bg-${colorScheme}-300/20`} />
        </div>
      </CardTitle>
      <div className="relative p-2">
        <div className={`absolute inset-0 rounded-full bg-${colorScheme}-300/20`} />
        <div className="h-5 w-5 relative rounded-full bg-${colorScheme}-300/20" />
      </div>
    </CardHeader>
    <CardContent className="p-4 pt-0">
      <div className="space-y-4">
        <div className="space-y-2">
          <Skeleton className={`h-8 w-32 bg-${colorScheme}-300/20`} />
          <div className="flex justify-between items-center">
            <div className="space-y-1">
              <Skeleton className={`h-4 w-24 bg-${colorScheme}-300/20`} />
            </div>
          </div>
        </div>
      </div>
    </CardContent>
  </Card>
);

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 fetch("/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) {
      return (
        <div>
          <div className="grid grid-cols-2 gap-2 mt-1 mb-2">
            <SkeletonCard colorScheme="sky" />
            <SkeletonCard colorScheme="sky" />
          </div>

          <Card className="bg-gradient-to-br from-sky-900 to-sky-800 backdrop-blur-sm">
            <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">
          {summaryCard(
            "Last 30 Minutes",
            "Active users",
            basicData.last30MinUsers,
            { 
              colorClass: "text-sky-200",
              titleClass: "text-sky-100 font-bold text-md",
              descriptionClass: "pt-2 text-sky-200 text-md font-semibold",
              background: "h-[150px] pt-2 bg-gradient-to-br from-sky-900 to-sky-800",
              icon: Users,
              iconColor: "text-sky-900",
              iconBackground: "bg-sky-300"
            }
          )}
          {summaryCard(
            "Last 5 Minutes",
            "Active users",
            basicData.last5MinUsers,
            { 
              colorClass: "text-sky-200",
              titleClass: "text-sky-100 font-bold text-md",
              descriptionClass: "pt-2 text-sky-200 text-md font-semibold",
              background: "h-[150px] pt-2 bg-gradient-to-br from-sky-900 to-sky-800",
              icon: Activity,
              iconColor: "text-sky-900",
              iconBackground: "bg-sky-300"
            }
          )}
        </div>

        <Card className="bg-gradient-to-br from-sky-900 to-sky-800 backdrop-blur-sm">
          <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) {
                        return (
                          <Card className="p-2 shadow-lg bg-sky-800 border-none">
                            <CardContent className="p-0 space-y-1">
                              <p className="font-medium text-sm text-sky-100 border-b border-sky-700 pb-1 mb-1">
                                {payload[0].payload.timestamp}
                              </p>
                              <div className="flex justify-between items-center text-sm">
                                <span className="text-sky-200">
                                  Active Users:
                                </span>
                                <span className="font-medium ml-4 text-sky-100">
                                  {payload[0].value}
                                </span>
                              </div>
                            </CardContent>
                          </Card>
                        );
                      }
                      return null;
                    }}
                  />
                  <Bar dataKey="users" fill="#0EA5E9" />
                </BarChart>
              </ResponsiveContainer>
            </div>
          </CardContent>
        </Card>
      </div>
    );
  };

  return renderContent();
};

export default MiniRealtimeAnalytics; 