import React, { useState, useEffect } from "react";
import { apiFetch } from "@/utils/api";
import { Card, CardContent } from "@/components/ui/card";
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from "@/components/ui/select";
import { Button } from "@/components/ui/button";
import {
  LineChart,
  Line,
  XAxis,
  YAxis,
  CartesianGrid,
  Tooltip,
  Legend,
  ResponsiveContainer,
} from "recharts";
import { TrendingUp } from "lucide-react";
import { Skeleton } from "@/components/ui/skeleton";
import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogTrigger } from "@/components/ui/dialog";
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/components/ui/table";
import { CARD_STYLES } from "@/lib/dashboard/designTokens";
import {
  DashboardSectionHeader,
  DashboardStatCard,
  DashboardStatCardSkeleton,
  DashboardChartTooltip,
  ChartSkeleton,
  DashboardEmptyState,
} from "@/components/dashboard/shared";

// Note: Using ChartSkeleton from @/components/dashboard/shared

const SkeletonStats = () => (
  <div className="grid grid-cols-2 lg:grid-cols-4 gap-4 py-4">
    {[...Array(4)].map((_, i) => (
      <DashboardStatCardSkeleton key={i} size="compact" hasIcon={false} hasSubtitle />
    ))}
  </div>
);

// Note: Using shared DashboardStatCard from @/components/dashboard/shared

// 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 apiFetch(
          `/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) {
          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();

  // Time selector for DashboardSectionHeader
  const timeSelector = (
    <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>
  );

  // Header actions: Details dialog
  const headerActions = !loading ? (
    <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 ${CARD_STYLES.base}`}>
        <DialogHeader className="flex-none">
          <DialogTitle className="text-foreground">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 ${CARD_STYLES.base} 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>
  ) : <Skeleton className="h-9 w-20 bg-muted rounded-sm" />;

  // Label formatter for chart tooltip
  const analyticsLabelFormatter = (label) => {
    const date = label instanceof Date ? label : new Date(label);
    return date.toLocaleDateString("en-US", { month: "short", day: "numeric" });
  };

  return (
    <Card className={`w-full ${CARD_STYLES.base}`}>
      <DashboardSectionHeader
        title="Analytics Overview"
        loading={loading}
        timeSelector={timeSelector}
        actions={headerActions}
      />

      <CardContent className="p-6 pt-0 space-y-4">
        {/* Stats cards */}
        {loading ? (
          <SkeletonStats />
        ) : summaryStats ? (
          <div className="grid grid-cols-2 lg:grid-cols-4 gap-4 dashboard-stagger">
            <DashboardStatCard
              title="Active Users"
              value={summaryStats.totals.activeUsers.toLocaleString()}
              subtitle={`Avg: ${Math.round(
                summaryStats.averages.activeUsers
              ).toLocaleString()} per day`}
              size="compact"
            />
            <DashboardStatCard
              title="New Users"
              value={summaryStats.totals.newUsers.toLocaleString()}
              subtitle={`Avg: ${Math.round(
                summaryStats.averages.newUsers
              ).toLocaleString()} per day`}
              size="compact"
            />
            <DashboardStatCard
              title="Page Views"
              value={summaryStats.totals.pageViews.toLocaleString()}
              subtitle={`Avg: ${Math.round(
                summaryStats.averages.pageViews
              ).toLocaleString()} per day`}
              size="compact"
            />
            <DashboardStatCard
              title="Conversions"
              value={summaryStats.totals.conversions.toLocaleString()}
              subtitle={`Avg: ${Math.round(
                summaryStats.averages.conversions
              ).toLocaleString()} per day`}
              size="compact"
            />
          </div>
        ) : null}

        {/* Metric toggles */}
        <div className="flex items-center flex-col sm:flex-row gap-0 sm:gap-4">
          <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>
        {loading ? (
          <ChartSkeleton height="default" withCard={false} />
        ) : !data.length ? (
          <DashboardEmptyState
            icon={TrendingUp}
            title="No analytics data available"
            description="Try selecting a different time range"
          />
        ) : (
          <div className={`h-[400px] mt-4 ${CARD_STYLES.base} 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={
                    <DashboardChartTooltip
                      labelFormatter={analyticsLabelFormatter}
                      valueFormatter={(value) => value.toLocaleString()}
                    />
                  }
                />
                <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; 