import React, { useState, useEffect } from "react";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/dashboard/ui/card";
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from "@/components/dashboard/ui/select";
import { Button } from "@/components/dashboard/ui/button";
import { Separator } from "@/components/dashboard/ui/separator";
import {
  LineChart,
  Line,
  XAxis,
  YAxis,
  CartesianGrid,
  Tooltip,
  Legend,
  ResponsiveContainer,
  ReferenceLine,
} from "recharts";
import { Loader2, TrendingUp, AlertCircle } from "lucide-react";
import { Alert, AlertDescription, AlertTitle } from "@/components/dashboard/ui/alert";
import { Skeleton } from "@/components/dashboard/ui/skeleton";
import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogTrigger } from "@/components/dashboard/ui/dialog";
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/components/dashboard/ui/table";

// Add helper function for currency formatting
const formatCurrency = (value, useFractionDigits = true) => {
  if (typeof value !== "number") return "$0.00";
  const roundedValue = parseFloat(value.toFixed(useFractionDigits ? 2 : 0));
  return new Intl.NumberFormat("en-US", {
    style: "currency",
    currency: "USD",
    minimumFractionDigits: useFractionDigits ? 2 : 0,
    maximumFractionDigits: useFractionDigits ? 2 : 0,
  }).format(roundedValue);
};

// Add skeleton components
const SkeletonChart = () => (
  <div className="h-[400px] w-full bg-white dark:bg-gray-900/60 backdrop-blur-sm rounded-lg p-6">
    <div className="h-full flex flex-col">
      <div className="flex-1 relative">
        {/* Grid lines */}
        {[...Array(5)].map((_, i) => (
          <div
            key={i}
            className="absolute w-full h-px bg-muted"
            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-muted 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-muted rounded-sm" />
          ))}
        </div>
        {/* Chart line */}
        <div className="absolute inset-x-8 bottom-6 top-4">
          <div className="h-full w-full relative">
            <div
              className="absolute inset-0 bg-muted rounded-sm"
              style={{
                opacity: 0.5,
                clipPath: "polygon(0 50%, 100% 20%, 100% 100%, 0 100%)",
              }}
            />
          </div>
        </div>
      </div>
    </div>
  </div>
);

const SkeletonStats = () => (
  <div className="grid grid-cols-2 lg:grid-cols-4 gap-4 py-4">
    {[...Array(4)].map((_, i) => (
      <Card key={i} className="bg-white dark:bg-gray-900/60 backdrop-blur-sm">
        <CardHeader className="flex flex-row items-center justify-between space-y-0 p-4 pb-2">
          <Skeleton className="h-4 w-24 bg-muted rounded-sm" />
        </CardHeader>
        <CardContent className="p-4 pt-0">
          <Skeleton className="h-8 w-32 bg-muted rounded-sm mb-2" />
          <Skeleton className="h-4 w-24 bg-muted rounded-sm" />
        </CardContent>
      </Card>
    ))}
  </div>
);

const SkeletonButtons = () => (
  <div className="flex flex-wrap gap-1">
    {[...Array(4)].map((_, i) => (
      <Skeleton key={i} className="h-8 w-20 bg-muted rounded-sm" />
    ))}
  </div>
);

// Add StatCard component
const StatCard = ({
  title,
  value,
  description,
  trend,
  trendValue,
  colorClass = "text-gray-900 dark:text-gray-100",
}) => (
  <Card className="bg-white dark:bg-gray-900/60 backdrop-blur-sm">
    <CardHeader className="flex flex-row items-center justify-between space-y-0 p-4 pb-2">
      <span className="text-sm text-muted-foreground font-medium">{title}</span>
      {trend && (
        <span
          className={`text-sm flex items-center gap-1 font-medium ${
            trend === "up"
              ? "text-emerald-600 dark:text-emerald-400"
              : "text-rose-600 dark:text-rose-400"
          }`}
        >
          {trendValue}
        </span>
      )}
    </CardHeader>
    <CardContent className="p-4 pt-0">
      <div className={`text-2xl font-bold mb-1.5 ${colorClass}`}>{value}</div>
      {description && (
        <div className="text-sm font-medium text-muted-foreground">{description}</div>
      )}
    </CardContent>
  </Card>
);

// Add color constants
const METRIC_COLORS = {
  activeUsers: {
    color: "#8b5cf6",
    className: "text-purple-600 dark:text-purple-400",
  },
  newUsers: {
    color: "#10b981",
    className: "text-emerald-600 dark:text-emerald-400",
  },
  pageViews: {
    color: "#f59e0b",
    className: "text-amber-600 dark:text-amber-400",
  },
  conversions: {
    color: "#3b82f6",
    className: "text-blue-600 dark:text-blue-400",
  },
};

export const AnalyticsDashboard = () => {
  const [data, setData] = useState([]);
  const [loading, setLoading] = useState(true);
  const [timeRange, setTimeRange] = useState("30");
  const [metrics, setMetrics] = useState({
    activeUsers: true,
    newUsers: true,
    pageViews: true,
    conversions: true,
  });

  useEffect(() => {
    const fetchData = async () => {
      setLoading(true);
      try {
        const response = await fetch(
          `/api/dashboard-analytics/metrics?startDate=${timeRange}daysAgo`,
          {
            credentials: "include",
          }
        );

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

        const result = await response.json();

        if (!result?.data?.rows) {
          console.log("No result data received");
          return;
        }

        const processedData = result.data.rows.map((row) => ({
          date: formatGADate(row.dimensionValues[0].value),
          activeUsers: parseInt(row.metricValues[0].value),
          newUsers: parseInt(row.metricValues[1].value),
          avgSessionDuration: parseFloat(row.metricValues[2].value),
          pageViews: parseInt(row.metricValues[3].value),
          bounceRate: parseFloat(row.metricValues[4].value) * 100,
          conversions: parseInt(row.metricValues[5].value),
        }));

        const sortedData = processedData.sort((a, b) => a.date - b.date);
        setData(sortedData);
      } catch (error) {
        console.error("Failed to fetch analytics:", error);
      } finally {
        setLoading(false);
      }
    };
    fetchData();
  }, [timeRange]);

  const formatGADate = (gaDate) => {
    const year = gaDate.substring(0, 4);
    const month = gaDate.substring(4, 6);
    const day = gaDate.substring(6, 8);
    return new Date(year, month - 1, day);
  };

  const formatXAxis = (date) => {
    if (!date) return "";
    return date.toLocaleDateString([], { month: "short", day: "numeric" });
  };

  const calculateSummaryStats = () => {
    if (!data.length) return null;

    const totals = data.reduce(
      (acc, day) => ({
        activeUsers: acc.activeUsers + day.activeUsers,
        newUsers: acc.newUsers + day.newUsers,
        pageViews: acc.pageViews + day.pageViews,
        conversions: acc.conversions + day.conversions,
      }),
      {
        activeUsers: 0,
        newUsers: 0,
        pageViews: 0,
        conversions: 0,
      }
    );

    const averages = {
      activeUsers: totals.activeUsers / data.length,
      newUsers: totals.newUsers / data.length,
      pageViews: totals.pageViews / data.length,
      conversions: totals.conversions / data.length,
    };

    return { totals, averages };
  };

  const summaryStats = calculateSummaryStats();

  const CustomTooltip = ({ active, payload, label }) => {
    if (active && payload && payload.length) {
      return (
        <Card className="p-3 shadow-lg bg-white dark:bg-gray-900/60 backdrop-blur-sm border border-border">
          <CardContent className="p-0 space-y-2">
            <p className="font-medium text-sm border-b border-border pb-1.5 mb-2 text-foreground">
              {label instanceof Date ? label.toLocaleDateString() : label}
            </p>
            <div className="space-y-1.5">
              {payload.map((entry, index) => (
                <div
                  key={index}
                  className="flex justify-between items-center text-sm"
                >
                  <span className="font-medium" style={{ color: entry.color }}>{entry.name}:</span>
                  <span className="font-medium ml-4 text-foreground">
                    {entry.value.toLocaleString()}
                  </span>
                </div>
              ))}
            </div>
          </CardContent>
        </Card>
      );
    }
    return null;
  };

  return (
    <Card className="w-full bg-white dark:bg-gray-900/60 backdrop-blur-sm">
      <CardHeader className="p-6 pb-4">
        <div className="flex flex-col space-y-2">
          <div className="flex justify-between items-start">
            <div>
              <CardTitle className="text-xl font-semibold text-gray-900 dark:text-gray-100">
                Analytics Overview
              </CardTitle>
            </div>
            <div className="flex items-center gap-2">
              {loading ? (
                <Skeleton className="h-9 w-[130px] bg-muted rounded-sm" />
              ) : (
                <>
                  <Dialog>
                    <DialogTrigger asChild>
                      <Button variant="outline" className="h-9">
                        Details
                      </Button>
                    </DialogTrigger>
                    <DialogContent className="max-w-[95vw] w-fit max-h-[85vh] overflow-hidden flex flex-col bg-white dark:bg-gray-900/60 backdrop-blur-sm">
                      <DialogHeader className="flex-none">
                        <DialogTitle className="text-gray-900 dark:text-gray-100">Daily Details</DialogTitle>
                        <div className="flex items-center justify-center gap-2 pt-4">
                          <div className="flex flex-wrap gap-1">
                            {Object.entries(metrics).map(([key, value]) => (
                              <Button
                                key={key}
                                variant={value ? "default" : "outline"}
                                size="sm"
                                onClick={() =>
                                  setMetrics((prev) => ({
                                    ...prev,
                                    [key]: !prev[key],
                                  }))
                                }
                              >
                                {key === "activeUsers" ? "Active Users" :
                                 key === "newUsers" ? "New Users" :
                                 key === "pageViews" ? "Page Views" :
                                 "Conversions"}
                              </Button>
                            ))}
                          </div>
                        </div>
                      </DialogHeader>
                      <div className="flex-1 overflow-y-auto mt-6">
                        <div className="rounded-lg border bg-white dark:bg-gray-900/60 backdrop-blur-sm w-full">
                          <Table className="w-full">
                            <TableHeader>
                              <TableRow>
                                <TableHead className="text-center whitespace-nowrap px-6 w-[120px]">Date</TableHead>
                                {metrics.activeUsers && (
                                  <TableHead className="text-center whitespace-nowrap px-6 min-w-[100px]">Active Users</TableHead>
                                )}
                                {metrics.newUsers && (
                                  <TableHead className="text-center whitespace-nowrap px-6 min-w-[100px]">New Users</TableHead>
                                )}
                                {metrics.pageViews && (
                                  <TableHead className="text-center whitespace-nowrap px-6 min-w-[140px]">Page Views</TableHead>
                                )}
                                {metrics.conversions && (
                                  <TableHead className="text-center whitespace-nowrap px-6 min-w-[120px]">Conversions</TableHead>
                                )}
                              </TableRow>
                            </TableHeader>
                            <TableBody>
                              {data.map((day) => (
                                <TableRow key={day.date}>
                                  <TableCell className="text-center whitespace-nowrap px-6">{formatXAxis(day.date)}</TableCell>
                                  {metrics.activeUsers && (
                                    <TableCell className="text-center whitespace-nowrap px-6">
                                      {day.activeUsers.toLocaleString()}
                                    </TableCell>
                                  )}
                                  {metrics.newUsers && (
                                    <TableCell className="text-center whitespace-nowrap px-6">
                                      {day.newUsers.toLocaleString()}
                                    </TableCell>
                                  )}
                                  {metrics.pageViews && (
                                    <TableCell className="text-center whitespace-nowrap px-6">
                                      {day.pageViews.toLocaleString()}
                                    </TableCell>
                                  )}
                                  {metrics.conversions && (
                                    <TableCell className="text-center whitespace-nowrap px-6">
                                      {day.conversions.toLocaleString()}
                                    </TableCell>
                                  )}
                                </TableRow>
                              ))}
                            </TableBody>
                          </Table>
                        </div>
                      </div>
                    </DialogContent>
                  </Dialog>
                  <Select value={timeRange} onValueChange={setTimeRange}>
                    <SelectTrigger className="w-[130px] h-9">
                      <SelectValue placeholder="Select range" />
                    </SelectTrigger>
                    <SelectContent>
                      <SelectItem value="7">Last 7 days</SelectItem>
                      <SelectItem value="14">Last 14 days</SelectItem>
                      <SelectItem value="30">Last 30 days</SelectItem>
                      <SelectItem value="90">Last 90 days</SelectItem>
                    </SelectContent>
                  </Select>
                </>
              )}
            </div>
          </div>

          {loading ? (
            <SkeletonStats />
          ) : summaryStats ? (
            <div className="grid grid-cols-2 lg:grid-cols-4 gap-4 py-4">
              <StatCard
                title="Active Users"
                value={summaryStats.totals.activeUsers.toLocaleString()}
                description={`Avg: ${Math.round(
                  summaryStats.averages.activeUsers
                ).toLocaleString()} per day`}
                colorClass={METRIC_COLORS.activeUsers.className}
              />
              <StatCard
                title="New Users"
                value={summaryStats.totals.newUsers.toLocaleString()}
                description={`Avg: ${Math.round(
                  summaryStats.averages.newUsers
                ).toLocaleString()} per day`}
                colorClass={METRIC_COLORS.newUsers.className}
              />
              <StatCard
                title="Page Views"
                value={summaryStats.totals.pageViews.toLocaleString()}
                description={`Avg: ${Math.round(
                  summaryStats.averages.pageViews
                ).toLocaleString()} per day`}
                colorClass={METRIC_COLORS.pageViews.className}
              />
              <StatCard
                title="Conversions"
                value={summaryStats.totals.conversions.toLocaleString()}
                description={`Avg: ${Math.round(
                  summaryStats.averages.conversions
                ).toLocaleString()} per day`}
                colorClass={METRIC_COLORS.conversions.className}
              />
            </div>
          ) : null}

          <div className="flex items-center flex-col sm:flex-row gap-0 sm:gap-4 pt-2">
            <div className="flex flex-wrap gap-1">
              <Button
                variant={metrics.activeUsers ? "default" : "outline"}
                size="sm"
                className="font-medium"
                onClick={() =>
                  setMetrics((prev) => ({
                    ...prev,
                    activeUsers: !prev.activeUsers,
                  }))
                }
              >
                <span className="hidden sm:inline">Active Users</span>
                <span className="sm:hidden">Active</span>
              </Button>
              <Button
                variant={metrics.newUsers ? "default" : "outline"}
                size="sm"
                className="font-medium"
                onClick={() =>
                  setMetrics((prev) => ({
                    ...prev,
                    newUsers: !prev.newUsers,
                  }))
                }
              >
                <span className="hidden sm:inline">New Users</span>
                <span className="sm:hidden">New</span>
              </Button>
              <Button
                variant={metrics.pageViews ? "default" : "outline"}
                size="sm"
                className="font-medium"
                onClick={() =>
                  setMetrics((prev) => ({
                    ...prev,
                    pageViews: !prev.pageViews,
                  }))
                }
              >
                <span className="hidden sm:inline">Page Views</span>
                <span className="sm:hidden">Views</span>
              </Button>
              <Button
                variant={metrics.conversions ? "default" : "outline"}
                size="sm"
                className="font-medium"
                onClick={() =>
                  setMetrics((prev) => ({
                    ...prev,
                    conversions: !prev.conversions,
                  }))
                }
              >
                <span className="hidden sm:inline">Conversions</span>
                <span className="sm:hidden">Conv.</span>
              </Button>
            </div>
          </div>
        </div>
      </CardHeader>

      <CardContent className="p-6 pt-0">
        {loading ? (
          <SkeletonChart />
        ) : !data.length ? (
          <div className="flex items-center justify-center h-[400px] text-muted-foreground">
            <div className="text-center">
              <TrendingUp className="h-12 w-12 mx-auto mb-4 opacity-50" />
              <div className="font-medium mb-2 text-gray-900 dark:text-gray-100">No analytics data available</div>
              <div className="text-sm text-muted-foreground">
                Try selecting a different time range
              </div>
            </div>
          </div>
        ) : (
          <div className="h-[400px] mt-4 bg-white dark:bg-gray-900/60 backdrop-blur-sm rounded-lg p-0 relative">
            <ResponsiveContainer width="100%" height="100%">
              <LineChart
                data={data}
                margin={{ top: 5, right: -30, left: -5, bottom: 5 }}
              >
                <CartesianGrid
                  strokeDasharray="3 3"
                  className="stroke-muted"
                />
                <XAxis
                  dataKey="date"
                  tickFormatter={formatXAxis}
                  className="text-xs text-muted-foreground"
                  tick={{ fill: "currentColor" }}
                />
                <YAxis
                  yAxisId="left"
                  className="text-xs text-muted-foreground"
                  tick={{ fill: "currentColor" }}
                />
                <YAxis
                  yAxisId="right"
                  orientation="right"
                  className="text-xs text-muted-foreground"
                  tick={{ fill: "currentColor" }}
                />
                <Tooltip content={<CustomTooltip />} />
                <Legend />
                {metrics.activeUsers && (
                  <Line
                    yAxisId="left"
                    type="monotone"
                    dataKey="activeUsers"
                    name="Active Users"
                    stroke={METRIC_COLORS.activeUsers.color}
                    strokeWidth={2}
                    dot={false}
                  />
                )}
                {metrics.newUsers && (
                  <Line
                    yAxisId="left"
                    type="monotone"
                    dataKey="newUsers"
                    name="New Users"
                    stroke={METRIC_COLORS.newUsers.color}
                    strokeWidth={2}
                    dot={false}
                  />
                )}
                {metrics.pageViews && (
                  <Line
                    yAxisId="right"
                    type="monotone"
                    dataKey="pageViews"
                    name="Page Views"
                    stroke={METRIC_COLORS.pageViews.color}
                    strokeWidth={2}
                    dot={false}
                  />
                )}
                {metrics.conversions && (
                  <Line
                    yAxisId="right"
                    type="monotone"
                    dataKey="conversions"
                    name="Conversions"
                    stroke={METRIC_COLORS.conversions.color}
                    strokeWidth={2}
                    dot={false}
                  />
                )}
              </LineChart>
            </ResponsiveContainer>
          </div>
        )}
      </CardContent>
    </Card>
  );
};

export default AnalyticsDashboard; 