/**
 * StatisticsCards Component
 *
 * Overview statistics cards showing key metrics for the Info Center:
 * - Total Analysed Pages
 * - Total Analyzed Pages
 * - Total Elements
 * - Coverage Percentage
 * - Reliability Status Breakdown
 * - Elements by Type breakdown
 *
 * @component
 * @layer Presentation
 */

import { Database, FileText, Box, TrendingUp, Activity, CheckCircle } from 'lucide-react';
import type { InfoCenterStats } from '../../presentation/features/info-center/hooks';
import { ElementType } from '@domain/entities';
import { ReliabilityStatus } from '@archer/domain';
import { ELEMENT_TYPE_CONFIG } from '@domain/constants';
import { ReliabilityStatusBadge } from '@/components/ui/ReliabilityStatusBadge';

interface StatisticsCardsProps {
  stats: InfoCenterStats;
}

/**
 * Format date to readable string
 */
function formatDate(dateStr?: string): string {
  if (!dateStr) return 'Never';
  const date = new Date(dateStr);
  return date.toLocaleDateString('en-US', { month: 'short', day: 'numeric', year: 'numeric' });
}

/**
 * StatisticsCards Component
 */
export function StatisticsCards({ stats }: StatisticsCardsProps) {
  // Get top element types (sorted by count)
  const topElementTypes = Object.entries(stats.elementsByType)
    .filter(([_, count]) => count > 0)
    .sort(([, a], [, b]) => b - a)
    .slice(0, 5);

  // Calculate reliability statistics
  const confirmedCount = stats.analysesByReliability[ReliabilityStatus.CONFIRMED] || 0;
  const pendingCount = stats.analysesByReliability[ReliabilityStatus.PENDING_CONFIRMATION] || 0;
  const draftCount = stats.analysesByReliability[ReliabilityStatus.DRAFT] || 0;
  const rejectedCount = stats.analysesByReliability[ReliabilityStatus.REJECTED] || 0;

  const totalWithReliability = confirmedCount + pendingCount + draftCount + rejectedCount;

  const confirmationRate =
    totalWithReliability > 0
      ? Math.round((confirmedCount / totalWithReliability) * 100)
      : 0;

  return (
    <div className="space-y-6">
      {/* Main Stats Grid */}
      <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-5 gap-6">
        {/* Total Analysed Pages */}
        <div className="bg-card rounded-lg border border-border p-6 shadow-sm">
          <div className="flex items-center justify-between mb-4">
            <div className="flex-shrink-0 w-12 h-12 rounded-lg bg-blue-100 flex items-center justify-center">
              <Database className="w-6 h-6 text-blue-600" />
            </div>
            <span className="text-sm font-medium text-muted-foreground">Total</span>
          </div>
          <div className="space-y-1">
            <div className="text-3xl font-bold text-foreground">
              {stats.totalCrawledPages}
            </div>
            <div className="text-sm text-muted-foreground">Analysed Pages</div>
            {stats.lastCrawlDate && (
              <div className="text-xs text-muted-foreground mt-2">
                Last crawl: {formatDate(stats.lastCrawlDate)}
              </div>
            )}
          </div>
        </div>

        {/* Total Analyzed Pages */}
        <div className="bg-card rounded-lg border border-border p-6 shadow-sm">
          <div className="flex items-center justify-between mb-4">
            <div className="flex-shrink-0 w-12 h-12 rounded-lg bg-green-100 flex items-center justify-center">
              <FileText className="w-6 h-6 text-green-600" />
            </div>
            <span className="text-sm font-medium text-muted-foreground">Analyzed</span>
          </div>
          <div className="space-y-1">
            <div className="text-3xl font-bold text-foreground">
              {stats.totalAnalyzedPages}
            </div>
            <div className="text-sm text-muted-foreground">Analyzed Pages</div>
            {stats.lastAnalysisDate && (
              <div className="text-xs text-muted-foreground mt-2">
                Last analysis: {formatDate(stats.lastAnalysisDate)}
              </div>
            )}
          </div>
        </div>

        {/* Total Elements */}
        <div className="bg-card rounded-lg border border-border p-6 shadow-sm">
          <div className="flex items-center justify-between mb-4">
            <div className="flex-shrink-0 w-12 h-12 rounded-lg bg-purple-100 flex items-center justify-center">
              <Box className="w-6 h-6 text-purple-600" />
            </div>
            <span className="text-sm font-medium text-muted-foreground">Discovered</span>
          </div>
          <div className="space-y-1">
            <div className="text-3xl font-bold text-foreground">
              {stats.totalElements.toLocaleString()}
            </div>
            <div className="text-sm text-muted-foreground">Total Elements</div>
            {stats.totalAnalyzedPages > 0 && (
              <div className="text-xs text-muted-foreground mt-2">
                Avg: {Math.round(stats.totalElements / stats.totalAnalyzedPages)} per page
              </div>
            )}
          </div>
        </div>

        {/* Coverage Percentage */}
        <div className="bg-card rounded-lg border border-border p-6 shadow-sm">
          <div className="flex items-center justify-between mb-4">
            <div className="flex-shrink-0 w-12 h-12 rounded-lg bg-orange-100 flex items-center justify-center">
              <TrendingUp className="w-6 h-6 text-orange-600" />
            </div>
            <span className="text-sm font-medium text-muted-foreground">Coverage</span>
          </div>
          <div className="space-y-1">
            <div className="text-3xl font-bold text-foreground">
              {stats.coveragePercentage}%
            </div>
            <div className="text-sm text-muted-foreground">Analysis Coverage</div>
            {/* Progress Bar */}
            <div className="mt-3 w-full bg-gray-200 rounded-full h-2">
              <div
                className="bg-orange-500 h-2 rounded-full transition-all duration-500"
                style={{ width: `${stats.coveragePercentage}%` }}
              />
            </div>
          </div>
        </div>

        {/* Reliability Status */}
        <div className="bg-card rounded-lg border border-border p-6 shadow-sm">
          <div className="flex items-center justify-between mb-4">
            <div className="flex-shrink-0 w-12 h-12 rounded-lg bg-cyan-100 flex items-center justify-center">
              <CheckCircle className="w-6 h-6 text-cyan-600" />
            </div>
            <span className="text-sm font-medium text-muted-foreground">Reliability</span>
          </div>
          <div className="space-y-1">
            <div className="text-3xl font-bold text-foreground">
              {confirmationRate}%
            </div>
            <div className="text-sm text-muted-foreground">Confirmation Rate</div>
            {/* Reliability Breakdown */}
            <div className="mt-3 grid grid-cols-2 gap-2 text-xs">
              <div className="flex items-center gap-1.5">
                <ReliabilityStatusBadge status={ReliabilityStatus.CONFIRMED} size="sm" showIcon={false} />
                <span className="text-muted-foreground font-medium">
                  {confirmedCount}
                </span>
              </div>
              <div className="flex items-center gap-1.5">
                <ReliabilityStatusBadge status={ReliabilityStatus.PENDING_CONFIRMATION} size="sm" showIcon={false} />
                <span className="text-muted-foreground font-medium">
                  {pendingCount}
                </span>
              </div>
              <div className="flex items-center gap-1.5">
                <ReliabilityStatusBadge status={ReliabilityStatus.DRAFT} size="sm" showIcon={false} />
                <span className="text-muted-foreground font-medium">
                  {draftCount}
                </span>
              </div>
              <div className="flex items-center gap-1.5">
                <ReliabilityStatusBadge status={ReliabilityStatus.REJECTED} size="sm" showIcon={false} />
                <span className="text-muted-foreground font-medium">
                  {rejectedCount}
                </span>
              </div>
            </div>
          </div>
        </div>
      </div>

      {/* Elements by Type Breakdown */}
      {topElementTypes.length > 0 && (
        <div className="bg-card rounded-lg border border-border p-6 shadow-sm">
          <div className="flex items-center gap-3 mb-4">
            <div className="flex-shrink-0 w-10 h-10 rounded-lg bg-cyan-100 flex items-center justify-center">
              <Activity className="w-5 h-5 text-cyan-600" />
            </div>
            <div>
              <h3 className="text-lg font-semibold text-foreground">Elements by Type</h3>
              <p className="text-sm text-muted-foreground">Distribution of discovered element types</p>
            </div>
          </div>

          <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-5 gap-4">
            {topElementTypes.map(([type, count]) => {
              const config = ELEMENT_TYPE_CONFIG[type as ElementType];
              const percentage = Math.round((count / stats.totalElements) * 100);

              return (
                <div key={type} className="space-y-2">
                  <div className="flex items-center justify-between">
                    <span className="text-sm font-medium text-foreground">{config.label}</span>
                    <span className="text-xs text-muted-foreground">{percentage}%</span>
                  </div>
                  <div className="text-2xl font-bold text-foreground">{count}</div>
                  <div className="w-full bg-gray-200 rounded-full h-1.5">
                    <div
                      className={`bg-${config.color}-500 h-1.5 rounded-full transition-all duration-500`}
                      style={{ width: `${percentage}%` }}
                    />
                  </div>
                </div>
              );
            })}
          </div>
        </div>
      )}
    </div>
  );
}
