import { Activity, ArrowDown, ArrowUp, Minus } from 'lucide-react';

import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/Components/ui/card';
import { CountUp } from '@/Components/ui/count-up';
import { EmptyState } from '@/Components/ui/empty-state';
import { formatDateTime, formatDecimal } from '@/lib/format';
import { cn } from '@/lib/utils';

import HealthScoreBadge from './HealthScoreBadge';

interface HealthScoreCardProps {
  score: number | null;
  previousScore: number | null;
  calculatedAt: string | null;
  siteId?: number;
}

type TrendIndicator = 'improving' | 'declining' | 'stable';

function getTrendIndicator(score: number | null, previousScore: number | null): TrendIndicator {
  if (score === null || previousScore === null) {
    return 'stable';
  }

  const delta = score - previousScore;

  if (delta >= 5) {
    return 'improving';
  } else if (delta <= -5) {
    return 'declining';
  } else {
    return 'stable';
  }
}

function TrendBadge({ trend, delta }: { trend: TrendIndicator; delta: number | null }) {
  if (delta === null || delta === 0) {
    return (
      <div className="inline-flex items-center gap-1.5 text-sm text-muted-foreground">
        <Minus className="h-4 w-4" />
        <span className="font-medium">No change</span>
      </div>
    );
  }

  const isPositive = delta > 0;

  return (
    <div
      className={cn(
        'inline-flex items-center gap-1.5 text-sm font-medium',
        isPositive ? 'text-green-600 dark:text-green-400' : 'text-red-600 dark:text-red-400',
        trend === 'stable' && 'text-muted-foreground',
      )}
    >
      {isPositive ? <ArrowUp className="h-4 w-4" /> : <ArrowDown className="h-4 w-4" />}
      <span>
        {isPositive ? '+' : ''}
        {formatDecimal(delta, 1)} points
      </span>
    </div>
  );
}

export default function HealthScoreCard({
  score,
  previousScore,
  calculatedAt,
  siteId: _siteId,
}: HealthScoreCardProps) {
  const trend = getTrendIndicator(score, previousScore);
  const delta = score !== null && previousScore !== null ? score - previousScore : null;

  return (
    <Card>
      <CardHeader>
        <CardTitle>Site Health Score</CardTitle>
        <CardDescription>
          Overall SEO health based on traffic, content quality, and recommendation completion
        </CardDescription>
      </CardHeader>
      <CardContent>
        {score === null ? (
          <EmptyState
            icon={Activity}
            title="No health score yet"
            description="Your site health score aggregates traffic trends, recommendation completion, and connection stability. Run your first analysis to calculate it."
            size="sm"
            animated={false}
          />
        ) : (
          <div className="flex flex-col gap-6">
            {/* Main Score Display */}
            <div className="flex items-baseline justify-between">
              <div className="flex items-baseline gap-3">
                <div className="text-5xl font-bold tabular-nums">
                  <CountUp end={score} />
                </div>
                <div className="text-xl text-muted-foreground">/100</div>
              </div>
              <HealthScoreBadge score={score} />
            </div>

            {/* Trend Indicator */}
            {previousScore !== null && (
              <div className="flex flex-col gap-2 rounded-lg bg-muted/50 p-3">
                <div className="text-xs font-medium uppercase tracking-wide text-muted-foreground">
                  Since Last Analysis
                </div>
                <TrendBadge trend={trend} delta={delta} />
              </div>
            )}

            {/* Last Calculated */}
            {calculatedAt && (
              <div className="text-xs text-muted-foreground">
                Last calculated {formatDateTime(calculatedAt)}
              </div>
            )}
          </div>
        )}
      </CardContent>
    </Card>
  );
}
