import { useEffect, useState, useMemo, lazy, Suspense } from "react";
import { Link, useNavigate } from "react-router";
import PageMeta from "../../components/common/PageMeta";
import ComponentCard from "../../components/common/ComponentCard";
import { ProgressBar } from "../../components/ui/progress";
import { ApexOptions } from "apexcharts";
import WorkflowPipeline, { WorkflowStep } from "../../components/dashboard/WorkflowPipeline";
import EnhancedMetricCard from "../../components/dashboard/EnhancedMetricCard";

const Chart = lazy(() => import("react-apexcharts").then((mod) => ({ default: mod.default })));
import { 
  ListIcon, 
  GroupIcon, 
  BoltIcon, 
  PieChartIcon, 
  ArrowRightIcon, 
  CheckCircleIcon, 
  TimeIcon,
  ArrowUpIcon,
  ArrowDownIcon
} from "../../icons";
import { 
  fetchKeywords, 
  fetchClusters, 
  fetchContentIdeas,
  fetchTasks
} from "../../services/api";
import { useSiteStore } from "../../store/siteStore";
import { useSectorStore } from "../../store/sectorStore";
import SectorSelector from "../../components/common/SectorSelector";

interface DashboardStats {
  keywords: {
    total: number;
    mapped: number;
    unmapped: number;
    byStatus: Record<string, number>;
    byIntent: Record<string, number>;
  };
  clusters: {
    total: number;
    withIdeas: number;
    withoutIdeas: number;
    totalVolume: number;
    avgKeywords: number;
    topClusters: Array<{ id: number; name: string; volume: number; keywords_count: number }>;
  };
  ideas: {
    total: number;
    queued: number;
    notQueued: number;
    byStatus: Record<string, number>;
    byContentType: Record<string, number>;
  };
  workflow: {
    keywordsReady: boolean;
    clustersBuilt: boolean;
    ideasGenerated: boolean;
    readyForWriter: boolean;
  };
}

export default function PlannerDashboard() {
  const navigate = useNavigate();
  const { activeSite } = useSiteStore();
  const { activeSector } = useSectorStore();
  
  const [stats, setStats] = useState<DashboardStats | null>(null);
  const [loading, setLoading] = useState(true);
  const [lastUpdated, setLastUpdated] = useState<Date>(new Date());
  const [trends, setTrends] = useState<{
    keywords: number;
    clusters: number;
    ideas: number;
  }>({ keywords: 0, clusters: 0, ideas: 0 });

  // Fetch real data
  const fetchDashboardData = async () => {
    try {
      setLoading(true);
      
      // Fetch all data in parallel
      const [keywordsRes, clustersRes, ideasRes, tasksRes] = await Promise.all([
        fetchKeywords({ page_size: 1000, sector_id: activeSector?.id }),
        fetchClusters({ page_size: 1000, sector_id: activeSector?.id }),
        fetchContentIdeas({ page_size: 1000, sector_id: activeSector?.id }),
        fetchTasks({ page_size: 1000, sector_id: activeSector?.id })
      ]);

      // Process keywords
      const keywords = keywordsRes.results || [];
      const mappedKeywords = keywords.filter(k => k.cluster && k.cluster.length > 0);
      const unmappedKeywords = keywords.filter(k => !k.cluster || k.cluster.length === 0);
      
      const keywordsByStatus: Record<string, number> = {};
      const keywordsByIntent: Record<string, number> = {};
      keywords.forEach(k => {
        keywordsByStatus[k.status || 'unknown'] = (keywordsByStatus[k.status || 'unknown'] || 0) + 1;
        if (k.intent) {
          keywordsByIntent[k.intent] = (keywordsByIntent[k.intent] || 0) + 1;
        }
      });

      // Process clusters
      const clusters = clustersRes.results || [];
      const clustersWithIdeas = clusters.filter(c => c.keywords_count > 0);
      const totalVolume = clusters.reduce((sum, c) => sum + (c.volume || 0), 0);
      const totalKeywordsInClusters = clusters.reduce((sum, c) => sum + (c.keywords_count || 0), 0);
      const avgKeywords = clusters.length > 0 ? Math.round(totalKeywordsInClusters / clusters.length) : 0;
      
      // Top clusters by volume
      const topClusters = [...clusters]
        .sort((a, b) => (b.volume || 0) - (a.volume || 0))
        .slice(0, 5)
        .map(c => ({
          id: c.id,
          name: c.name || 'Unnamed Cluster',
          volume: c.volume || 0,
          keywords_count: c.keywords_count || 0
        }));

      // Process ideas
      const ideas = ideasRes.results || [];
      const ideaIds = new Set(ideas.map(i => i.id));
      const tasks = tasksRes.results || [];
      const queuedIdeas = tasks.filter(t => t.idea && ideaIds.has(t.idea)).length;
      const notQueuedIdeas = ideas.length - queuedIdeas;
      
      const ideasByStatus: Record<string, number> = {};
      const ideasByContentType: Record<string, number> = {};
      ideas.forEach(i => {
        ideasByStatus[i.status || 'new'] = (ideasByStatus[i.status || 'new'] || 0) + 1;
        if (i.content_type) {
          ideasByContentType[i.content_type] = (ideasByContentType[i.content_type] || 0) + 1;
        }
      });

      // Calculate trends (compare with previous state)
      if (stats) {
        setTrends({
          keywords: keywords.length - stats.keywords.total,
          clusters: clusters.length - stats.clusters.total,
          ideas: ideas.length - stats.ideas.total
        });
      }

      setStats({
        keywords: {
          total: keywords.length,
          mapped: mappedKeywords.length,
          unmapped: unmappedKeywords.length,
          byStatus: keywordsByStatus,
          byIntent: keywordsByIntent
        },
        clusters: {
          total: clusters.length,
          withIdeas: clustersWithIdeas.length,
          withoutIdeas: clusters.length - clustersWithIdeas.length,
          totalVolume,
          avgKeywords,
          topClusters
        },
        ideas: {
          total: ideas.length,
          queued: queuedIdeas,
          notQueued: notQueuedIdeas,
          byStatus: ideasByStatus,
          byContentType: ideasByContentType
        },
        workflow: {
          keywordsReady: keywords.length > 0,
          clustersBuilt: clusters.length > 0,
          ideasGenerated: ideas.length > 0,
          readyForWriter: queuedIdeas > 0
        }
      });

      setLastUpdated(new Date());
    } catch (error) {
      console.error('Error fetching dashboard data:', error);
    } finally {
      setLoading(false);
    }
  };

  // Initial load and periodic refresh
  useEffect(() => {
    // Allow loading for all sectors (when activeSector is null) or specific sector
    fetchDashboardData();
    
    // Refresh every 30 seconds
    const interval = setInterval(fetchDashboardData, 30000);
    
    return () => clearInterval(interval);
  }, [activeSector?.id, activeSite?.id]);

  // Calculate percentages
  const keywordMappingPct = useMemo(() => {
    if (!stats || stats.keywords.total === 0) return 0;
    return Math.round((stats.keywords.mapped / stats.keywords.total) * 100);
  }, [stats]);

  const clustersIdeasPct = useMemo(() => {
    if (!stats || stats.clusters.total === 0) return 0;
    return Math.round((stats.clusters.withIdeas / stats.clusters.total) * 100);
  }, [stats]);

  const ideasQueuedPct = useMemo(() => {
    if (!stats || stats.ideas.total === 0) return 0;
    return Math.round((stats.ideas.queued / stats.ideas.total) * 100);
  }, [stats]);

  // Chart data for keywords by status
  const keywordsStatusChart = useMemo(() => {
    if (!stats) return null;
    
    const options: ApexOptions = {
      chart: {
        type: 'donut',
        fontFamily: 'Outfit, sans-serif',
        toolbar: { show: false }
      },
      labels: Object.keys(stats.keywords.byStatus).filter(key => stats.keywords.byStatus[key] > 0),
      colors: ['#465FFF', '#10B981', '#F59E0B', '#EF4444', '#8B5CF6'],
      legend: {
        position: 'bottom',
        fontFamily: 'Outfit',
        show: true
      },
      dataLabels: {
        enabled: false // Disable labels on pie slices
      },
      tooltip: {
        enabled: true,
        y: {
          formatter: (val: number, { seriesIndex, w }: any) => {
            const label = w.globals.labels[seriesIndex] || '';
            return `${label}: ${val}`;
          }
        }
      },
      plotOptions: {
        pie: {
          donut: {
            size: '70%',
            labels: {
              show: true,
              name: {
                show: false // Hide "Total" label
              },
              value: {
                show: true,
                fontSize: '24px',
                fontWeight: 700,
                color: '#465FFF',
                fontFamily: 'Outfit',
                formatter: () => {
                  const total = Object.values(stats.keywords.byStatus).reduce((a, b) => a + b, 0);
                  return total > 0 ? total.toString() : '0';
                }
              },
              total: {
                show: false // Hide total label
              }
            }
          }
        }
      }
    };

    const series = Object.keys(stats.keywords.byStatus)
      .filter(key => stats.keywords.byStatus[key] > 0)
      .map(key => stats.keywords.byStatus[key]);
    
    return { options, series };
  }, [stats]);

  // Chart data for ideas by status
  const ideasStatusChart = useMemo(() => {
    if (!stats) return null;
    
    const options: ApexOptions = {
      chart: {
        type: 'bar',
        fontFamily: 'Outfit, sans-serif',
        toolbar: { show: false },
        height: 250
      },
      colors: ['#465FFF'],
      plotOptions: {
        bar: {
          horizontal: false,
          columnWidth: '55%',
          borderRadius: 5
        }
      },
      dataLabels: {
        enabled: true
      },
      xaxis: {
        categories: Object.keys(stats.ideas.byStatus),
        labels: {
          style: {
            fontFamily: 'Outfit'
          }
        }
      },
      yaxis: {
        labels: {
          style: {
            fontFamily: 'Outfit'
          }
        }
      },
      grid: {
        strokeDashArray: 4
      }
    };

    const series = [{
      name: 'Ideas',
      data: Object.values(stats.ideas.byStatus)
    }];
    
    return { options, series };
  }, [stats]);

  // Chart data for top clusters volume
  const topClustersChart = useMemo(() => {
    if (!stats || stats.clusters.topClusters.length === 0) return null;
    
    const options: ApexOptions = {
      chart: {
        type: 'bar',
        fontFamily: 'Outfit, sans-serif',
        toolbar: { show: false },
        height: 300
      },
      colors: ['#10B981'],
      plotOptions: {
        bar: {
          horizontal: true,
          borderRadius: 5,
          dataLabels: {
            position: 'top'
          }
        }
      },
      dataLabels: {
        enabled: true,
        formatter: (val: number) => val.toLocaleString(),
        offsetX: 10
      },
      xaxis: {
        categories: stats.clusters.topClusters.map(c => c.name),
        labels: {
          style: {
            fontFamily: 'Outfit',
            fontSize: '12px'
          }
        }
      },
      yaxis: {
        labels: {
          style: {
            fontFamily: 'Outfit'
          }
        }
      },
      tooltip: {
        y: {
          formatter: (val: number) => `${val.toLocaleString()} volume`
        }
      }
    };

    const series = [{
      name: 'Search Volume',
      data: stats.clusters.topClusters.map(c => c.volume)
    }];
    
    return { options, series };
  }, [stats]);

  if (loading && !stats) {
    return (
      <>
        <PageMeta title="Planner Dashboard - IGNY8" description="Content planning overview" />
        <div className="flex items-center justify-center h-96">
          <div className="text-center">
            <div className="inline-block animate-spin rounded-full h-12 w-12 border-4 border-brand-500 border-t-transparent"></div>
            <p className="mt-4 text-gray-600 dark:text-gray-400">Loading dashboard data...</p>
          </div>
        </div>
      </>
    );
  }

  if (!stats && !loading) {
    return (
      <>
        <PageMeta title="Planner Dashboard - IGNY8" description="Content planning overview" />
        <div className="text-center py-12">
          <p className="text-gray-600 dark:text-gray-400">
            {activeSector ? 'No data available for the selected sector.' : 'No data available. Select a sector or wait for data to load.'}
          </p>
        </div>
      </>
    );
  }

  if (!stats) {
    return null; // Still loading
  }

  const workflowSteps = [
    { 
      number: 1, 
      title: "Add Keywords", 
      status: stats.workflow.keywordsReady ? "completed" : "pending", 
      count: stats.keywords.total, 
      path: "/planner/keywords" 
    },
    { 
      number: 2, 
      title: "Auto Cluster", 
      status: stats.workflow.clustersBuilt ? "completed" : "pending", 
      count: stats.clusters.total, 
      path: "/planner/clusters" 
    },
    { 
      number: 3, 
      title: "Generate Ideas", 
      status: stats.workflow.ideasGenerated ? "completed" : "pending", 
      count: stats.ideas.total, 
      path: "/planner/ideas" 
    },
    { 
      number: 4, 
      title: "Queue to Writer", 
      status: stats.workflow.readyForWriter ? "completed" : "pending", 
      count: stats.ideas.queued, 
      path: "/writer/tasks" 
    },
  ];

  const nextActions = [
    ...(stats.keywords.unmapped > 0 ? [{
      text: `${stats.keywords.unmapped} keywords unmapped`,
      action: "Map Keywords",
      path: "/planner/keywords"
    }] : []),
    ...(stats.clusters.withoutIdeas > 0 ? [{
      text: `${stats.clusters.withoutIdeas} clusters without ideas`,
      action: "Generate Ideas",
      path: "/planner/clusters"
    }] : []),
    ...(stats.ideas.notQueued > 0 ? [{
      text: `${stats.ideas.notQueued} ideas not queued to writer`,
      action: "Queue to Writer",
      path: "/planner/ideas"
    }] : [])
  ];

  return (
    <>
      <PageMeta title="Planner Dashboard - IGNY8" description="Content planning overview" />
      
      <div className="space-y-5 sm:space-y-6">
        {/* Header with site/sector info and controls */}
        <div className="flex flex-col sm:flex-row items-start sm:items-center justify-between gap-4">
          <div className="flex-1">
            <h2 className="text-2xl font-bold text-gray-800 dark:text-white/90">Planner Dashboard</h2>
            <div className="flex items-center gap-3 mt-1">
              <p className="text-sm text-gray-500 dark:text-gray-400">
                Last updated: {lastUpdated.toLocaleTimeString()}
              </p>
              {activeSite && (
                <>
                  <span className="text-sm text-gray-400 dark:text-gray-600">•</span>
                  <p className="text-sm font-medium text-gray-700 dark:text-gray-300">
                    Site: <span className="text-brand-600 dark:text-brand-400">{activeSite.name}</span>
                  </p>
                </>
              )}
              {activeSector && (
                <>
                  <span className="text-sm text-gray-400 dark:text-gray-600">•</span>
                  <p className="text-sm font-medium text-gray-700 dark:text-gray-300">
                    Sector: <span className="text-brand-600 dark:text-brand-400">{activeSector.name}</span>
                  </p>
                </>
              )}
              {!activeSector && (
                <>
                  <span className="text-sm text-gray-400 dark:text-gray-600">•</span>
                  <p className="text-sm font-medium text-gray-700 dark:text-gray-300">
                    Sector: <span className="text-brand-600 dark:text-brand-400">All Sectors</span>
                  </p>
                </>
              )}
            </div>
          </div>
          <div className="flex items-center gap-3">
            <SectorSelector />
            <button
              onClick={fetchDashboardData}
              className="px-4 py-2 text-sm font-medium text-brand-500 hover:text-brand-600 border border-brand-200 rounded-lg hover:bg-brand-50 dark:border-brand-800 dark:hover:bg-brand-500/10 transition-colors"
            >
              Refresh
            </button>
          </div>
        </div>

        {/* Hero Section - Key Metric */}
        <div className="rounded-2xl border border-gray-200 bg-gradient-to-br from-brand-50 to-white dark:from-brand-500/10 dark:to-gray-800/50 dark:border-gray-800 p-6 md:p-8">
          <div className="flex items-center justify-between">
            <div>
              <p className="text-sm font-medium text-gray-600 dark:text-gray-400">Planning Progress</p>
              <h3 className="mt-2 text-3xl font-bold text-gray-800 dark:text-white/90">
                {stats.ideas.queued > 0 ? (
                  <>
                    {stats.ideas.queued} Ideas Ready for Content Generation
                  </>
                ) : stats.ideas.total > 0 ? (
                  <>
                    {stats.ideas.total} Ideas Generated
                  </>
                ) : stats.clusters.total > 0 ? (
                  <>
                    {stats.clusters.total} Clusters Built
                  </>
                ) : (
                  <>
                    {stats.keywords.total} Keywords Ready
                  </>
                )}
              </h3>
              <p className="mt-2 text-sm text-gray-500 dark:text-gray-400">
                {stats.keywords.total} keywords • {stats.clusters.total} clusters • {stats.ideas.total} ideas
              </p>
            </div>
            <div className="hidden md:flex items-center gap-4">
              <div className="text-center">
                <div className="text-2xl font-bold text-brand-500">{keywordMappingPct}%</div>
                <div className="text-xs text-gray-500 dark:text-gray-400">Mapped</div>
              </div>
              <div className="text-center">
                <div className="text-2xl font-bold text-success-500">{clustersIdeasPct}%</div>
                <div className="text-xs text-gray-500 dark:text-gray-400">With Ideas</div>
              </div>
              <div className="text-center">
                <div className="text-2xl font-bold text-warning-500">{ideasQueuedPct}%</div>
                <div className="text-xs text-gray-500 dark:text-gray-400">Queued</div>
              </div>
            </div>
          </div>
        </div>

        {/* Enhanced Metric Cards */}
        <div className="grid grid-cols-1 gap-4 md:grid-cols-2 lg:grid-cols-4 md:gap-6">
          <EnhancedMetricCard
            title="Keywords Ready"
            value={stats.keywords.total}
            subtitle={`${stats.keywords.mapped} mapped • ${stats.keywords.unmapped} unmapped`}
            trend={trends.keywords}
            icon={<ListIcon className="size-6" />}
            accentColor="blue"
            href="/planner/keywords"
            details={[
              { label: "Total Keywords", value: stats.keywords.total },
              { label: "Mapped", value: stats.keywords.mapped },
              { label: "Unmapped", value: stats.keywords.unmapped },
              { label: "Active", value: stats.keywords.byStatus.active || 0 },
              { label: "Pending", value: stats.keywords.byStatus.pending || 0 },
            ]}
          />

          <EnhancedMetricCard
            title="Clusters Built"
            value={stats.clusters.total}
            subtitle={`${stats.clusters.totalVolume.toLocaleString()} total volume • ${stats.clusters.avgKeywords} avg keywords`}
            trend={trends.clusters}
            icon={<GroupIcon className="size-6" />}
            accentColor="green"
            href="/planner/clusters"
            details={[
              { label: "Total Clusters", value: stats.clusters.total },
              { label: "With Ideas", value: stats.clusters.withIdeas },
              { label: "Without Ideas", value: stats.clusters.withoutIdeas },
              { label: "Total Volume", value: stats.clusters.totalVolume.toLocaleString() },
              { label: "Avg Keywords", value: stats.clusters.avgKeywords },
            ]}
          />

          <EnhancedMetricCard
            title="Ideas Generated"
            value={stats.ideas.total}
            subtitle={`${stats.ideas.queued} queued • ${stats.ideas.notQueued} pending`}
            trend={trends.ideas}
            icon={<BoltIcon className="size-6" />}
            accentColor="orange"
            href="/planner/ideas"
            details={[
              { label: "Total Ideas", value: stats.ideas.total },
              { label: "Queued", value: stats.ideas.queued },
              { label: "Not Queued", value: stats.ideas.notQueued },
              { label: "New", value: stats.ideas.byStatus.new || 0 },
              { label: "Scheduled", value: stats.ideas.byStatus.scheduled || 0 },
            ]}
          />

          <EnhancedMetricCard
            title="Mapping Progress"
            value={`${keywordMappingPct}%`}
            subtitle={`${stats.keywords.mapped} of ${stats.keywords.total} keywords mapped`}
            icon={<PieChartIcon className="size-6" />}
            accentColor="purple"
            href="/planner/keywords"
            details={[
              { label: "Mapping Progress", value: `${keywordMappingPct}%` },
              { label: "Mapped Keywords", value: stats.keywords.mapped },
              { label: "Total Keywords", value: stats.keywords.total },
              { label: "Unmapped", value: stats.keywords.unmapped },
            ]}
          />
        </div>

      {/* Interactive Workflow Pipeline */}
      <ComponentCard title="Planner Workflow Pipeline" desc="Track your planning progress through each stage">
        <WorkflowPipeline
          steps={workflowSteps.map(step => ({
            number: step.number,
            title: step.title,
            status: step.status === "completed" ? "completed" : step.status === "in_progress" ? "in_progress" : "pending",
            count: step.count || 0,
            path: step.path,
            description: step.title,
            details: step.status === "completed" 
              ? `✓ ${step.title} completed with ${step.count} items`
              : step.status === "pending"
              ? `→ ${step.title} pending - ${step.count} items ready`
              : `⟳ ${step.title} in progress`,
          }))}
          onStepClick={(step) => {
            navigate(step.path);
          }}
          showConnections={true}
        />
      </ComponentCard>

      <div className="grid grid-cols-1 gap-6 lg:grid-cols-3">
        {/* Progress Summary */}
        <ComponentCard title="Progress & Readiness Summary" desc="Planning workflow progress tracking" className="lg:col-span-1">
          <div className="space-y-6">
            <div>
              <div className="flex items-center justify-between mb-2">
                <span className="text-sm font-medium text-gray-700 dark:text-gray-300">Keyword Mapping</span>
                <span className="text-sm font-semibold text-gray-800 dark:text-white/90">{keywordMappingPct}%</span>
              </div>
              <ProgressBar value={keywordMappingPct} color="primary" size="md" />
              <p className="mt-1 text-xs text-gray-500 dark:text-gray-400">
                  {stats.keywords.mapped} of {stats.keywords.total} keywords mapped
              </p>
            </div>

            <div>
              <div className="flex items-center justify-between mb-2">
                <span className="text-sm font-medium text-gray-700 dark:text-gray-300">Clusters With Ideas</span>
                <span className="text-sm font-semibold text-gray-800 dark:text-white/90">{clustersIdeasPct}%</span>
              </div>
              <ProgressBar value={clustersIdeasPct} color="success" size="md" />
              <p className="mt-1 text-xs text-gray-500 dark:text-gray-400">
                  {stats.clusters.withIdeas} of {stats.clusters.total} clusters have ideas
              </p>
            </div>

            <div>
              <div className="flex items-center justify-between mb-2">
                <span className="text-sm font-medium text-gray-700 dark:text-gray-300">Ideas Queued to Writer</span>
                <span className="text-sm font-semibold text-gray-800 dark:text-white/90">{ideasQueuedPct}%</span>
              </div>
              <ProgressBar value={ideasQueuedPct} color="warning" size="md" />
              <p className="mt-1 text-xs text-gray-500 dark:text-gray-400">
                  {stats.ideas.queued} of {stats.ideas.total} ideas queued
              </p>
            </div>
          </div>
        </ComponentCard>

          {/* Top 5 Clusters */}
          <ComponentCard title="Top 5 Clusters by Volume" desc="Highest volume keyword clusters" className="lg:col-span-2">
            {topClustersChart ? (
              <Suspense fallback={<div className="flex items-center justify-center h-[300px]"><div className="animate-spin rounded-full h-8 w-8 border-4 border-brand-500 border-t-transparent"></div></div>}>
                <Chart 
                  options={topClustersChart.options} 
                  series={topClustersChart.series} 
                  type="bar" 
                  height={300} 
                />
              </Suspense>
            ) : (
              <div className="text-center py-8 text-gray-500 dark:text-gray-400">
                No clusters data available
              </div>
            )}
          </ComponentCard>
          </div>

        <div className="grid grid-cols-1 gap-6 lg:grid-cols-2">
          {/* Keywords by Status */}
          {keywordsStatusChart && (
            <ComponentCard title="Keywords by Status" desc="Distribution of keywords across statuses">
              <Suspense fallback={<div className="flex items-center justify-center h-[300px]"><div className="animate-spin rounded-full h-8 w-8 border-4 border-brand-500 border-t-transparent"></div></div>}>
                <Chart 
                  options={keywordsStatusChart.options} 
                  series={keywordsStatusChart.series} 
                  type="donut" 
                  height={300} 
                />
              </Suspense>
            </ComponentCard>
          )}

          {/* Ideas by Status */}
          {ideasStatusChart && (
            <ComponentCard title="Ideas by Status" desc="Content ideas workflow status">
              <Suspense fallback={<div className="flex items-center justify-center h-[300px]"><div className="animate-spin rounded-full h-8 w-8 border-4 border-brand-500 border-t-transparent"></div></div>}>
                <Chart 
                  options={ideasStatusChart.options} 
                  series={ideasStatusChart.series} 
                  type="bar" 
                  height={300} 
                />
              </Suspense>
            </ComponentCard>
          )}
      </div>

      {/* Next Actions */}
        {nextActions.length > 0 && (
      <ComponentCard title="Next Actions" desc="Actionable items requiring attention">
        <div className="space-y-3">
          {nextActions.map((action, index) => (
            <div
              key={index}
                  className="flex items-center justify-between p-4 rounded-lg bg-gradient-to-r from-gray-50 to-white dark:from-gray-900/50 dark:to-gray-800/50 border border-gray-200 dark:border-gray-800 hover:border-brand-300 dark:hover:border-brand-500/30 transition-all group"
            >
                  <span className="text-sm font-medium text-gray-700 dark:text-gray-300">{action.text}</span>
              <Link
                to={action.path}
                    className="inline-flex items-center gap-2 text-sm font-medium text-brand-500 hover:text-brand-600 group-hover:translate-x-1 transition-transform"
              >
                {action.action}
                <ArrowRightIcon className="size-4" />
              </Link>
            </div>
          ))}
        </div>
      </ComponentCard>
        )}
      </div>
    </>
  );
}
