import { useState, useEffect } from 'react';
import { Card, CardContent, CardHeader, CardTitle, CardDescription } from '@/components/ui/card';
import { Button } from '@/components/ui/button';
import { Badge } from '@/components/ui/badge';
import { Tabs, TabsContent, TabsList, TabsTrigger } from '@/components/ui/tabs';
import { analytics } from '@/components/analytics/analytics-service';
import { 
  Users, 
  Activity, 
  TrendingUp, 
  AlertTriangle,
  Clock,
  MousePointer,
} from 'lucide-react';
import {
  XAxis,
  YAxis,
  CartesianGrid,
  Tooltip,
  ResponsiveContainer,
  BarChart,
  Bar,
  AreaChart,
  Area,
} from 'recharts';

export function AnalyticsDashboard() {
  const [data, setData] = useState(() => analytics.getAnalyticsData());
  const [refreshKey, setRefreshKey] = useState(0);

  // Refresh data periodically
  useEffect(() => {
    const interval = setInterval(() => {
      setData(analytics.getAnalyticsData());
    }, 30000); // Refresh every 30 seconds

    return () => clearInterval(interval);
  }, [refreshKey]);

  const handleRefresh = () => {
    setData(analytics.getAnalyticsData());
    setRefreshKey((k) => k + 1);
  };

  return (
    <div className="space-y-6">
      {/* Header */}
      <div className="flex justify-between items-center">
        <div>
          <h1 className="text-3xl font-bold">Analytics Dashboard</h1>
          <p className="text-muted-foreground">
            Usage metrics and performance insights
          </p>
        </div>
        <Button variant="outline" onClick={handleRefresh}>
          Refresh Data
        </Button>
      </div>

      {/* Key Metrics */}
      <div className="grid gap-4 md:grid-cols-2 lg:grid-cols-4">
        <MetricCard
          title="Monthly Active Users"
          value={data.mau}
          icon={Users}
          description="Unique sessions (30 days)"
        />
        <MetricCard
          title="Total Events"
          value={data.totalEvents.toLocaleString()}
          icon={Activity}
          description="Tracked events"
        />
        <MetricCard
          title="Top Feature"
          value={data.featureUsage[0]?.feature || 'N/A'}
          icon={MousePointer}
          description={`${data.featureUsage[0]?.count || 0} uses`}
        />
        <MetricCard
          title="Avg Load Time"
          value={`${(
            data.performanceMetrics.find((m) => m.metric === 'page_load')?.avg || 0
          ).toFixed(0)}ms`}
          icon={Clock}
          description="Page load performance"
        />
      </div>

      {/* Tabs for detailed views */}
      <Tabs defaultValue="users" className="space-y-4">
        <TabsList>
          <TabsTrigger value="users">User Activity</TabsTrigger>
          <TabsTrigger value="features">Feature Adoption</TabsTrigger>
          <TabsTrigger value="performance">Performance</TabsTrigger>
          <TabsTrigger value="costs">Cost Predictions</TabsTrigger>
        </TabsList>

        <TabsContent value="users" className="space-y-4">
          <Card>
            <CardHeader>
              <CardTitle>Daily Active Users</CardTitle>
              <CardDescription>User activity over the last 7 days</CardDescription>
            </CardHeader>
            <CardContent>
              <div className="h-[300px]">
                <ResponsiveContainer width="100%" height="100%">
                  <AreaChart data={data.dailyActiveUsers}>
                    <defs>
                      <linearGradient id="colorUsers" x1="0" y1="0" x2="0" y2="1">
                        <stop offset="5%" stopColor="hsl(var(--primary))" stopOpacity={0.3}/>
                        <stop offset="95%" stopColor="hsl(var(--primary))" stopOpacity={0}/>
                      </linearGradient>
                    </defs>
                    <CartesianGrid strokeDasharray="3 3" />
                    <XAxis dataKey="date" tickFormatter={(date) => new Date(date).toLocaleDateString()} />
                    <YAxis />
                    <Tooltip 
                      labelFormatter={(date) => new Date(date as string).toLocaleDateString()}
                    />
                    <Area
                      type="monotone"
                      dataKey="users"
                      stroke="hsl(var(--primary))"
                      fillOpacity={1}
                      fill="url(#colorUsers)"
                    />
                  </AreaChart>
                </ResponsiveContainer>
              </div>
            </CardContent>
          </Card>

          <Card>
            <CardHeader>
              <CardTitle>Popular Pages</CardTitle>
              <CardDescription>Most visited pages</CardDescription>
            </CardHeader>
            <CardContent>
              <div className="space-y-2">
                {data.pageViews.slice(0, 5).map((page) => (
                  <div key={page.path} className="flex justify-between items-center p-2 bg-muted/50 rounded">
                    <span className="font-mono text-sm">{page.path}</span>
                    <Badge variant="secondary">{page.count} views</Badge>
                  </div>
                ))}
              </div>
            </CardContent>
          </Card>
        </TabsContent>

        <TabsContent value="features" className="space-y-4">
          <Card>
            <CardHeader>
              <CardTitle>Feature Adoption</CardTitle>
              <CardDescription>Most used features</CardDescription>
            </CardHeader>
            <CardContent>
              <div className="h-[300px]">
                <ResponsiveContainer width="100%" height="100%">
                  <BarChart data={data.featureUsage} layout="vertical">
                    <CartesianGrid strokeDasharray="3 3" />
                    <XAxis type="number" />
                    <YAxis dataKey="feature" type="category" width={120} />
                    <Tooltip />
                    <Bar dataKey="count" fill="hsl(var(--primary))" />
                  </BarChart>
                </ResponsiveContainer>
              </div>
            </CardContent>
          </Card>
        </TabsContent>

        <TabsContent value="performance" className="space-y-4">
          <Card>
            <CardHeader>
              <CardTitle>Performance Metrics</CardTitle>
              <CardDescription>Application performance over time</CardDescription>
            </CardHeader>
            <CardContent>
              <div className="grid gap-4 md:grid-cols-2">
                {data.performanceMetrics.map((metric) => (
                  <Card key={metric.metric}>
                    <CardContent className="pt-6">
                      <div className="flex justify-between items-start">
                        <div>
                          <p className="text-sm text-muted-foreground capitalize">
                            {metric.metric.replace('_', ' ')}
                          </p>
                          <p className="text-2xl font-bold">
                            {metric.avg.toFixed(2)}ms
                          </p>
                        </div>
                        <Badge variant="outline">
                          {metric.count} samples
                        </Badge>
                      </div>
                      <div className="mt-2 text-xs text-muted-foreground">
                        Min: {metric.min.toFixed(0)}ms | Max: {metric.max.toFixed(0)}ms
                      </div>
                    </CardContent>
                  </Card>
                ))}
              </div>
            </CardContent>
          </Card>
        </TabsContent>

        <TabsContent value="costs" className="space-y-4">
          <CostPredictions predictions={data.costPredictions} />
        </TabsContent>
      </Tabs>
    </div>
  );
}

interface MetricCardProps {
  title: string;
  value: string | number;
  icon: React.ElementType;
  description?: string;
}

function MetricCard({ title, value, icon: Icon, description }: MetricCardProps) {
  return (
    <Card>
      <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
        <CardTitle className="text-sm font-medium">{title}</CardTitle>
        <Icon className="h-4 w-4 text-muted-foreground" />
      </CardHeader>
      <CardContent>
        <div className="text-2xl font-bold">{value}</div>
        {description && (
          <p className="text-xs text-muted-foreground mt-1">{description}</p>
        )}
      </CardContent>
    </Card>
  );
}

interface CostPredictionsProps {
  predictions: Array<{
    month: number;
    predicted: number;
    confidenceLow: number;
    confidenceHigh: number;
  }>;
}

function CostPredictions({ predictions }: CostPredictionsProps) {
  const [anomalies, setAnomalies] = useState<Array<{ index: number; cost: number; type: string }>>([]);

  // Simple anomaly detection simulation
  useEffect(() => {
    const mockHistoricalData = [950, 980, 1020, 990, 1010, 1050, 1000, 1100, 1300, 1020];
    const detected = analytics.detectAnomalies(mockHistoricalData);
    setAnomalies(
      detected.map((a) => ({
        index: a.index,
        cost: a.cost,
        type: a.type,
      }))
    );
  }, []);

  return (
    <div className="space-y-4">
      <Card>
        <CardHeader>
          <CardTitle className="flex items-center gap-2">
            <TrendingUp className="h-5 w-5" />
            Cost Forecast
          </CardTitle>
          <CardDescription>
            ML-based cost predictions for the next 3 months
          </CardDescription>
        </CardHeader>
        <CardContent>
          <div className="h-[300px]">
            <ResponsiveContainer width="100%" height="100%">
              <AreaChart
                data={[
                  { month: 'Current', value: 1000, low: 1000, high: 1000 },
                  ...predictions.map((p) => ({
                    month: `+${p.month}M`,
                    value: p.predicted,
                    low: p.confidenceLow,
                    high: p.confidenceHigh,
                  })),
                ]}
              >
                <defs>
                  <linearGradient id="colorConfidence" x1="0" y1="0" x2="0" y2="1">
                    <stop offset="5%" stopColor="hsl(var(--primary))" stopOpacity={0.2}/>
                    <stop offset="95%" stopColor="hsl(var(--primary))" stopOpacity={0.05}/>
                  </linearGradient>
                </defs>
                <CartesianGrid strokeDasharray="3 3" />
                <XAxis dataKey="month" />
                <YAxis tickFormatter={(v) => `$${v}`} />
                <Tooltip formatter={(v) => `$${Number(v).toFixed(2)}`} />
                <Area
                  type="monotone"
                  dataKey="high"
                  stroke="none"
                  fill="url(#colorConfidence)"
                />
                <Area
                  type="monotone"
                  dataKey="low"
                  stroke="none"
                  fill="white"
                />
                <Area
                  type="monotone"
                  dataKey="value"
                  stroke="hsl(var(--primary))"
                  strokeWidth={2}
                  fill="none"
                />
              </AreaChart>
            </ResponsiveContainer>
          </div>
          <div className="mt-4 flex items-center gap-2 text-sm text-muted-foreground">
            <div className="w-3 h-3 rounded-full bg-primary" />
            Predicted cost
            <div className="w-3 h-3 rounded-full bg-primary/20 ml-4" />
            Confidence interval
          </div>
        </CardContent>
      </Card>

      {anomalies.length > 0 && (
        <Card>
          <CardHeader>
            <CardTitle className="flex items-center gap-2 text-amber-500">
              <AlertTriangle className="h-5 w-5" />
              Detected Anomalies
            </CardTitle>
            <CardDescription>
              Unusual cost patterns detected in historical data
            </CardDescription>
          </CardHeader>
          <CardContent>
            <div className="space-y-2">
              {anomalies.map((anomaly, i) => (
                <div
                  key={i}
                  className="flex items-center gap-3 p-3 bg-amber-50 dark:bg-amber-950/20 rounded-lg border border-amber-200 dark:border-amber-800"
                >
                  <AlertTriangle className="h-5 w-5 text-amber-500" />
                  <div>
                    <p className="font-medium">
                      Cost {anomaly.type === 'spike' ? 'Spike' : 'Drop'} Detected
                    </p>
                    <p className="text-sm text-muted-foreground">
                      Day {anomaly.index + 1}: ${anomaly.cost.toFixed(2)}
                    </p>
                  </div>
                </div>
              ))}
            </div>
          </CardContent>
        </Card>
      )}
    </div>
  );
}
