import { format } from "date-fns";
import { Calendar, CheckCircle2, Clock, Layers } from "lucide-react";
import { Link } from "react-router";
import { SportIcon as SportSeasonIcon } from "~/components/SportIcon";
import { Badge } from "~/components/ui/badge";
import { Button } from "~/components/ui/button";
import { Card, CardContent, CardHeader } from "~/components/ui/card";
import { GradientIcon } from "~/components/ui/GradientIcon";
import type { UpcomingParticipantEvent } from "~/models/scoring-event";

// ─── Types ────────────────────────────────────────────────────────────────────

export interface DraftedParticipantSummary {
  id: string;
  name: string;
  /** Fantasy league points earned (position → scoring rules). null = no result yet. */
  earnedPoints: number | null;
  /** Accumulated qualifying points for qualifying_points sports. null for other sports. */
  currentQP: number | null;
}

export interface SportSeasonSummaryItem {
  id: string;
  sportName: string;
  sportIconUrl?: string | null;
  seasonName: string;
  status: "upcoming" | "active" | "completed";
  scoringPattern?: string | null;
  upcomingParticipantEvents?: UpcomingParticipantEvent[];
  /** All participants the current user drafted for this sport, with points data. */
  draftedParticipants?: DraftedParticipantSummary[];
}

export interface SportsSeasonsSummaryProps {
  leagueId: string;
  sportsSeasons: SportSeasonSummaryItem[];
  /** Link to the full sports seasons list, if one exists. */
  allSeasonsHref?: string;
}

// ─── Helpers ──────────────────────────────────────────────────────────────────

const STATUS_ORDER: Record<SportSeasonSummaryItem["status"], number> = {
  active: 0,
  upcoming: 1,
  completed: 2,
};

function sortedByStatus(items: SportSeasonSummaryItem[]): SportSeasonSummaryItem[] {
  return [...items].toSorted((a, b) => {
    const diff = STATUS_ORDER[a.status] - STATUS_ORDER[b.status];
    if (diff !== 0) return diff;
    return a.sportName.localeCompare(b.sportName);
  });
}

/** Format the next upcoming event into a short string. */
function formatNextEvent(event: UpcomingParticipantEvent): string {
  const base = event.matchLabel
    ? `${event.name} — ${event.matchLabel}`
    : event.name;

  const date = event.earliestGameTime
    ? format(new Date(event.earliestGameTime), "MMM d")
    : event.eventDate
    ? format(new Date(event.eventDate + "T00:00:00"), "MMM d")
    : null;

  return date ? `${base} · ${date}` : base;
}

function formatPoints(p: DraftedParticipantSummary, scoringPattern?: string | null): string | null {
  if (scoringPattern === "qualifying_points" && p.earnedPoints === null) {
    if (!p.currentQP) return null;
    return `${p.currentQP % 1 === 0 ? p.currentQP : p.currentQP.toFixed(1)} QP`;
  }
  if (p.earnedPoints === null) return null;
  return `${Math.round(p.earnedPoints)} pts`;
}

// ─── Section header ───────────────────────────────────────────────────────────

type SectionStatus = "active" | "upcoming" | "completed";

function SectionHeader({ status }: { status: SectionStatus }) {
  if (status === "active") {
    return (
      <div className="flex items-center gap-1.5 px-1 py-0.5">
        <span className="relative flex h-2 w-2 shrink-0">
          <span className="absolute inline-flex h-full w-full animate-ping rounded-full bg-emerald-500 opacity-60" />
          <span className="relative inline-flex h-2 w-2 rounded-full bg-emerald-500" />
        </span>
        <span className="text-xs font-semibold uppercase tracking-widest text-emerald-400">
          Active
        </span>
      </div>
    );
  }
  if (status === "upcoming") {
    return (
      <div className="flex items-center gap-1.5 px-1 py-0.5">
        <Clock className="h-3 w-3 text-electric shrink-0" />
        <span className="text-xs font-semibold uppercase tracking-widest text-electric">
          Upcoming
        </span>
      </div>
    );
  }
  return (
    <div className="flex items-center gap-1.5 px-1 py-0.5">
      <CheckCircle2 className="h-3 w-3 text-muted-foreground shrink-0" />
      <span className="text-xs font-semibold uppercase tracking-widest text-muted-foreground">
        Completed
      </span>
    </div>
  );
}

// ─── Participant chip ─────────────────────────────────────────────────────────

function ParticipantChip({
  participant,
  scoringPattern,
}: {
  participant: DraftedParticipantSummary;
  scoringPattern?: string | null;
}) {
  const pointsLabel = formatPoints(participant, scoringPattern);
  return (
    <Badge variant="secondary" className="text-xs h-5 px-1.5 shrink-0 gap-1 bg-white/[0.1]">
      <span>{participant.name}</span>
      {pointsLabel && (
        <span className="text-muted-foreground font-normal">· {pointsLabel}</span>
      )}
    </Badge>
  );
}

// ─── Single sport row ─────────────────────────────────────────────────────────

function SportRow({
  item,
  leagueId,
}: {
  item: SportSeasonSummaryItem;
  leagueId: string;
}) {
  const participants = item.draftedParticipants ?? [];
  const events = item.upcomingParticipantEvents ?? [];
  const nextEvent = events[0] ?? null;
  const isCompleted = item.status === "completed";

  const inner = (
    <div
      className={`group flex gap-3 rounded-lg px-3 py-2.5 overflow-hidden transition-colors ${
        isCompleted
          ? "hover:bg-white/[0.04] opacity-70 hover:opacity-100"
          : "hover:bg-white/[0.06]"
      }`}
    >
      {/* Left: sport icon */}
      <div className="flex h-9 w-9 shrink-0 items-center justify-center">
        <SportSeasonIcon
          sportName={item.sportName}
          iconUrl={item.sportIconUrl}
          size="md"
          decorative
        />
      </div>

      {/* Right: name + participants + next event */}
      <div className="flex-1 min-w-0">
        <p className="font-semibold text-sm leading-tight truncate">{item.sportName}</p>
        <p className="text-xs text-muted-foreground truncate mb-1.5">{item.seasonName}</p>

        {participants.length > 0 && (
          <div className="flex flex-wrap gap-1">
            {participants.map((p) => (
              <ParticipantChip key={p.id} participant={p} scoringPattern={item.scoringPattern} />
            ))}
          </div>
        )}

        {nextEvent && (
          <div className="flex items-center gap-1.5 text-xs text-muted-foreground mt-1.5">
            <Calendar className="h-3 w-3 text-electric shrink-0" />
            <span className="truncate" suppressHydrationWarning>
              {formatNextEvent(nextEvent)}
            </span>
          </div>
        )}
      </div>
    </div>
  );

  return (
    <Link
      to={`/leagues/${leagueId}/sports-seasons/${item.id}`}
      className="block min-w-0"
      aria-label={`${item.sportName} — ${item.seasonName}`}
    >
      {inner}
    </Link>
  );
}

// ─── Section ──────────────────────────────────────────────────────────────────

function Section({
  status,
  items,
  leagueId,
}: {
  status: SectionStatus;
  items: SportSeasonSummaryItem[];
  leagueId: string;
}) {
  if (items.length === 0) return null;

  return (
    <div className="space-y-1">
      <SectionHeader status={status} />
      <div className="grid gap-0.5 sm:grid-cols-2">
        {items.map((item) => (
          <SportRow key={item.id} item={item} leagueId={leagueId} />
        ))}
      </div>
    </div>
  );
}

// ─── Public API ───────────────────────────────────────────────────────────────

export function SportsSeasonsSummary({
  leagueId,
  sportsSeasons,
  allSeasonsHref,
}: SportsSeasonsSummaryProps) {
  const sorted = sortedByStatus(sportsSeasons);
  const active = sorted.filter((s) => s.status === "active");
  const upcoming = sorted.filter((s) => s.status === "upcoming");
  const completed = sorted.filter((s) => s.status === "completed");

  return (
    <Card className="gap-2">
      <CardHeader className="px-3 sm:px-6 pb-2">
        <div className="flex items-center justify-between">
          <div className="flex items-center gap-2">
            <GradientIcon icon={Layers} className="h-5 w-5 shrink-0" />
            <div>
              <h2 className="text-xl font-bold leading-none tracking-tight">Sports</h2>
            </div>
          </div>
          {allSeasonsHref && (
            <Button variant="outline" size="sm" asChild>
              <Link to={allSeasonsHref}>View All</Link>
            </Button>
          )}
        </div>
      </CardHeader>

      <CardContent className="px-3 sm:px-6 space-y-3">
        <Section status="active" items={active} leagueId={leagueId} />
        {active.length > 0 && upcoming.length > 0 && (
          <div className="border-t border-border/40" />
        )}
        <Section status="upcoming" items={upcoming} leagueId={leagueId} />
        {(active.length > 0 || upcoming.length > 0) && completed.length > 0 && (
          <div className="border-t border-border/40" />
        )}
        <Section status="completed" items={completed} leagueId={leagueId} />
      </CardContent>
    </Card>
  );
}
