import { useMemo, useCallback } from 'react';
import { useScenarios } from '@/hooks/useScenarios';
import { Activity, DollarSign, Server, AlertTriangle, TrendingUp } from 'lucide-react';
import { Card, CardContent, CardHeader, CardTitle, CardDescription } from '@/components/ui/card';
import { CostBreakdownChart } from '@/components/charts';
import { formatCurrency, formatNumber } from '@/components/charts/chart-utils';
import { Skeleton } from '@/components/ui/skeleton';
import { Link } from 'react-router-dom';
import { analytics, useFeatureTracking } from '@/components/analytics/analytics-service';
import { useTranslation } from 'react-i18next';

interface StatCardProps {
  title: string;
  value: string | number;
  description?: string;
  icon: React.ElementType;
  trend?: 'up' | 'down' | 'neutral';
  href?: string;
}

const StatCard = ({ 
  title, 
  value, 
  description, 
  icon: Icon,
  trend,
  href,
}: StatCardProps) => {
  const content = (
    <Card className={`transition-all hover:shadow-md ${href ? 'cursor-pointer' : ''}`}>
      <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" aria-hidden="true" />
      </CardHeader>
      <CardContent>
        <div className="text-2xl font-bold">{value}</div>
        {trend && (
          <div 
            className={`flex items-center text-xs mt-1 ${
              trend === 'up' ? 'text-green-500' : 
              trend === 'down' ? 'text-red-500' : 
              'text-muted-foreground'
            }`}
            aria-label={`Trend: ${trend}`}
          >
            <TrendingUp className="h-3 w-3 mr-1" aria-hidden="true" />
            {trend === 'up' ? 'Increasing' : trend === 'down' ? 'Decreasing' : 'Stable'}
          </div>
        )}
        {description && (
          <p className="text-xs text-muted-foreground mt-1">{description}</p>
        )}
      </CardContent>
    </Card>
  );

  if (href) {
    return (
      <Link to={href} className="block">
        {content}
      </Link>
    );
  }
  return content;
};

export function Dashboard() {
  const { t } = useTranslation();
  const { data: scenarios, isLoading: scenariosLoading } = useScenarios(1, 100);
  const trackFeature = useFeatureTracking();

  // Track dashboard view
  const trackDashboardClick = useCallback((feature: string) => {
    trackFeature(feature);
    analytics.trackFeatureUsage(`dashboard_click_${feature}`);
  }, [trackFeature]);

  // Aggregate metrics from all scenarios
  const totalScenarios = scenarios?.total || 0;
  const runningScenarios = useMemo(
    () => scenarios?.items.filter(s => s.status === 'running').length || 0,
    [scenarios?.items]
  );
  const totalCost = useMemo(
    () => scenarios?.items.reduce((sum, s) => sum + s.total_cost_estimate, 0) || 0,
    [scenarios?.items]
  );

  // Calculate cost breakdown
  const costBreakdown = useMemo(() => [
    { service: 'SQS', cost_usd: totalCost * 0.35, percentage: 35 },
    { service: 'Lambda', cost_usd: totalCost * 0.25, percentage: 25 },
    { service: 'Bedrock', cost_usd: totalCost * 0.40, percentage: 40 },
  ].filter(item => item.cost_usd > 0), [totalCost]);

  if (scenariosLoading) {
    return (
      <div className="space-y-6" role="status" aria-label="Loading dashboard">
        <Skeleton className="h-10 w-48" />
        <div className="grid gap-4 md:grid-cols-2 lg:grid-cols-4">
          {[...Array(4)].map((_, i) => (
            <Skeleton key={i} className="h-32" />
          ))}
        </div>
        <Skeleton className="h-[400px]" />
      </div>
    );
  }
  
  return (
    <div className="space-y-6">
      <div>
        <h1 className="text-3xl font-bold">{t('dashboard.title')}</h1>
        <p className="text-muted-foreground">
          {t('dashboard.subtitle')}
        </p>
      </div>
      
      <div 
        className="grid gap-4 md:grid-cols-2 lg:grid-cols-4"
        data-tour="dashboard-stats"
        role="region"
        aria-label="Key metrics"
      >
        <div onClick={() => trackDashboardClick('scenarios')}>
          <StatCard
            title={t('dashboard.total_scenarios')}
            value={formatNumber(totalScenarios)}
            description={t('dashboard.total_scenarios')}
            icon={Server}
            href="/scenarios"
          />
        </div>
        <StatCard
          title={t('dashboard.running_scenarios')}
          value={formatNumber(runningScenarios)}
          description="Active simulations"
          icon={Activity}
          trend={runningScenarios > 0 ? 'up' : 'neutral'}
        />
        <StatCard
          title={t('dashboard.total_cost')}
          value={formatCurrency(totalCost)}
          description="Estimated AWS costs"
          icon={DollarSign}
        />
        <StatCard
          title={t('dashboard.pii_violations')}
          value="0"
          description="Potential data leaks"
          icon={AlertTriangle}
          trend="neutral"
        />
      </div>

      {/* Charts Section */}
      <div className="grid gap-6 lg:grid-cols-2">
        {costBreakdown.length > 0 && (
          <CostBreakdownChart
            data={costBreakdown}
            title="Cost Breakdown"
            description="Estimated cost distribution by service"
          />
        )}
        
        <Card>
          <CardHeader>
            <CardTitle>{t('dashboard.recent_activity')}</CardTitle>
            <CardDescription>Latest scenario executions</CardDescription>
          </CardHeader>
          <CardContent>
            <div className="space-y-4">
              {scenarios?.items.slice(0, 5).map((scenario) => (
                <Link 
                  key={scenario.id} 
                  to={`/scenarios/${scenario.id}`}
                  className="flex items-center justify-between p-3 rounded-lg hover:bg-muted transition-colors"
                  onClick={() => trackDashboardClick('recent_scenario')}
                >
                  <div>
                    <p className="font-medium">{scenario.name}</p>
                    <p className="text-sm text-muted-foreground">{scenario.region}</p>
                  </div>
                  <div className="text-right">
                    <p className="font-medium">{formatCurrency(scenario.total_cost_estimate)}</p>
                    <p className="text-sm text-muted-foreground">
                      {formatNumber(scenario.total_requests)} requests
                    </p>
                  </div>
                </Link>
              ))}
              {(!scenarios?.items || scenarios.items.length === 0) && (
                <p className="text-center text-muted-foreground py-4">
                  No scenarios yet. Create one to get started.
                </p>
              )}
            </div>
          </CardContent>
        </Card>
      </div>

      {/* Quick Actions */}
      <Card>
        <CardHeader>
          <CardTitle>{t('dashboard.quick_actions')}</CardTitle>
        </CardHeader>
        <CardContent>
          <div className="flex flex-wrap gap-3">
            <Link to="/scenarios" onClick={() => trackDashboardClick('view_all')}>
              <button className="px-4 py-2 bg-primary text-primary-foreground rounded-md hover:bg-primary/90 transition-colors">
                View All Scenarios
              </button>
            </Link>
            <Link to="/analytics" onClick={() => trackDashboardClick('analytics')}>
              <button className="px-4 py-2 bg-secondary text-secondary-foreground rounded-md hover:bg-secondary/90 transition-colors">
                View Analytics
              </button>
            </Link>
          </div>
        </CardContent>
      </Card>
    </div>
  );
}
