"use client";

import { Check, X, AlertTriangle, TrendingUp, TrendingDown } from "lucide-react";
import { cn } from "@/shared/lib/utils";
import { useT } from "@/shared/i18n/client";
import { Card, CardContent, CardHeader, CardTitle } from "@/presentation/components/ui/card";
import { Progress } from "@/presentation/components/ui/progress";
import { Badge } from "@/presentation/components/ui/badge";
import { TIER_VAR, tierFromScore } from "../tier";
import type { HealthOverview } from "@/domain/entities/health";

const COMPONENT_KEYS = ["activity", "adoption", "frequency", "completeness", "growth"] as const;

export function OverviewTab({ overview }: { overview: HealthOverview }) {
  const t = useT();

  return (
    <div className="grid grid-cols-1 lg:grid-cols-2 gap-4">
      {/* Health score breakdown */}
      <Card>
        <CardHeader>
          <CardTitle className="text-base">{t.health.profile.breakdown}</CardTitle>
        </CardHeader>
        <CardContent className="space-y-3">
          {COMPONENT_KEYS.map((key) => {
            const c = overview.breakdown[key];
            const barValue = Math.max(0, Math.min(100, c.score));
            // Tier-colored bar (spec §1 tiers apply identically to bars on every
            // screen); a negative growth score reads at-risk red.
            const barColor = TIER_VAR[tierFromScore(c.score)];
            return (
              <div key={key} className={cn(!c.included && "opacity-45")}>
                <div className="flex items-center justify-between mb-1">
                  <span className="text-sm">
                    {t.health.profile.components[key]}
                    <span className="text-muted-foreground ml-1.5 text-xs">· {t.health.profile.weight(c.weight)}</span>
                  </span>
                  <span className="text-sm font-mono font-semibold">
                    {c.included ? Math.round(c.score) : t.health.profile.excluded}
                  </span>
                </div>
                <div className="h-2 rounded-full bg-muted overflow-hidden">
                  <div className="h-full rounded-full" style={{ width: `${barValue}%`, backgroundColor: barColor }} />
                </div>
              </div>
            );
          })}
        </CardContent>
      </Card>

      {/* Adoption alerts */}
      <Card>
        <CardHeader>
          <CardTitle className="text-base flex items-center gap-2">
            {t.health.profile.alerts}
            <Badge
              className={cn(
                "text-xs border-0 px-1.5",
                overview.adoption_alerts.length > 0
                  ? "bg-amber-100 text-amber-700 dark:bg-amber-950/40 dark:text-amber-400"
                  : "bg-muted text-muted-foreground"
              )}
            >
              {overview.adoption_alerts.length}
            </Badge>
          </CardTitle>
        </CardHeader>
        <CardContent>
          {overview.adoption_alerts.length === 0 ? (
            <div className="flex items-center gap-2 py-6 justify-center text-sm text-muted-foreground">
              <Check className="w-4 h-4 text-emerald-500" />
              {t.health.profile.noAlerts}
            </div>
          ) : (
            <div className="space-y-2.5">
              {overview.adoption_alerts.map((a, i) => (
                <div key={i} className="flex items-start gap-2.5">
                  <AlertTriangle
                    className={cn("w-4 h-4 mt-0.5 flex-shrink-0", a.severity === "red" ? "text-red-500" : "text-amber-500")}
                  />
                  <span className="text-sm">{a.message}</span>
                </div>
              ))}
            </div>
          )}
        </CardContent>
      </Card>

      {/* Engagement trend */}
      <Card>
        <CardHeader>
          <CardTitle className="text-base">{t.health.profile.engagementTrend}</CardTitle>
        </CardHeader>
        <CardContent>
          <div className="flex items-end gap-6">
            <div>
              <p className="text-3xl font-bold font-mono leading-none">
                {overview.engagement_trend.current.toLocaleString()}
              </p>
              <p className="text-xs text-muted-foreground mt-1">
                {t.health.profile.thisMonth} · {t.health.profile.actionsLower}
              </p>
            </div>
            <div
              className={cn(
                "flex items-center gap-1 text-sm font-semibold pb-1",
                overview.engagement_trend.change_pct >= 0 ? "text-emerald-600" : "text-red-500"
              )}
            >
              {overview.engagement_trend.change_pct >= 0 ? <TrendingUp className="w-4 h-4" /> : <TrendingDown className="w-4 h-4" />}
              {overview.engagement_trend.change_pct >= 0 ? "+" : ""}
              {overview.engagement_trend.change_pct}%
            </div>
          </div>
          <p className="text-xs text-muted-foreground mt-2">
            {t.health.profile.lastMonth}: <span className="font-mono">{overview.engagement_trend.previous.toLocaleString()}</span>
          </p>
        </CardContent>
      </Card>

      {/* Fleet maturity */}
      <Card>
        <CardHeader>
          <CardTitle className="text-base flex items-center justify-between">
            {t.health.profile.fleetMaturity}
            <span className="text-2xl font-bold font-mono">{overview.fleet_maturity.percent}%</span>
          </CardTitle>
        </CardHeader>
        <CardContent className="space-y-3">
          <Progress value={overview.fleet_maturity.percent} />
          <div className="grid grid-cols-2 gap-2">
            {overview.fleet_maturity.items.map((item) => (
              <div key={item.key} className="flex items-center gap-2 text-sm">
                {item.done ? (
                  <Check className="w-4 h-4 text-emerald-500 flex-shrink-0" />
                ) : (
                  <X className="w-4 h-4 text-muted-foreground/50 flex-shrink-0" />
                )}
                <span className={cn("truncate", !item.done && "text-muted-foreground")}>
                  {maturityLabel(t, item.key)}
                </span>
              </div>
            ))}
          </div>
        </CardContent>
      </Card>
    </div>
  );
}

function maturityLabel(t: ReturnType<typeof useT>, key: string): string {
  const items = t.health.profile.maturityItems as Record<string, string>;
  return items[key] ?? key;
}
