import React from "react";
import { Card, CardContent, CardHeader, CardTitle } from "./card";
import { Spinner } from "./spinner";
import { cn } from "@/lib/utils";
import { formatCurrency } from "@/lib/format-currency";

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

export interface IncomeSource {
  id: string;
  label: string;
  amount: number;
  /** 0–100, percentage of total income */
  percentage: number;
  transactionCount?: number;
}

export interface IncomeSourcesCardProps {
  sources: IncomeSource[];
  totalIncome: number;
  selectedSourceId?: string | null;
  onSelectSource?: (id: string | null) => void;
  /** Display label for the period, e.g. "30 Days" */
  period?: string;
  isLoading?: boolean;
  className?: string;
}

// ─── Source row ───────────────────────────────────────────────────────────────

function SourceRow({
  source,
  isSelected,
  onClick,
}: {
  source: IncomeSource;
  isSelected: boolean;
  onClick: () => void;
}) {
  return (
    <button
      type="button"
      onClick={onClick}
      aria-pressed={isSelected}
      className={cn(
        "flex w-full flex-col gap-1.5 border-b border-l-2 border-border py-3 pl-3 text-left transition-colors last:border-0",
        isSelected
          ? "border-l-primary bg-primary/5 hover:bg-primary/10"
          : "border-l-transparent hover:bg-muted/50",
      )}
    >
      <div className="flex items-baseline justify-between gap-3">
        <span
          className={cn(
            "truncate text-sm font-medium",
            isSelected ? "text-primary" : "text-foreground",
          )}
        >
          {source.label}
        </span>
        <span className="shrink-0 text-sm font-semibold text-foreground">
          {formatCurrency(source.amount)}
        </span>
      </div>

      <div className="flex items-center justify-between gap-2">
        <span className="text-xs text-muted-foreground">
          {source.transactionCount != null
            ? `${source.transactionCount} ${source.transactionCount === 1 ? "transaction" : "transactions"}`
            : ""}
        </span>
        <span className="text-xs text-muted-foreground">
          {source.percentage.toFixed(0)}%
        </span>
      </div>

      <div className="h-1.5 w-full overflow-hidden bg-muted">
        <div
          className="h-full bg-primary transition-all"
          style={{ width: `${Math.min(100, Math.max(0, source.percentage))}%` }}
          aria-hidden="true"
        />
      </div>
    </button>
  );
}

// ─── Component ────────────────────────────────────────────────────────────────

export function IncomeSourcesCard({
  sources,
  totalIncome,
  selectedSourceId,
  onSelectSource,
  period,
  isLoading = false,
  className,
}: IncomeSourcesCardProps) {
  return (
    <Card className={cn("flex flex-col", className)}>
      <CardHeader className="pb-2">
        <div className="flex items-start justify-between gap-2">
          <CardTitle className="text-xs font-semibold uppercase tracking-wider text-muted-foreground">
            Income Sources
          </CardTitle>
          <div className="flex shrink-0 flex-col items-end">
            <span className="text-sm font-semibold text-foreground">
              {formatCurrency(totalIncome)}
            </span>
            {period && (
              <span className="text-xs text-muted-foreground">{period}</span>
            )}
          </div>
        </div>
      </CardHeader>

      <CardContent className="flex flex-1 flex-col p-0 px-4 pb-2">
        {isLoading ? (
          <div className="flex flex-1 items-center justify-center py-8">
            <Spinner size="default" />
          </div>
        ) : sources.length === 0 ? (
          <p className="py-8 text-center text-sm text-muted-foreground">
            No income sources available
          </p>
        ) : (
          sources.map((source) => (
            <SourceRow
              key={source.id}
              source={source}
              isSelected={selectedSourceId === source.id}
              onClick={() =>
                onSelectSource?.(
                  selectedSourceId === source.id ? null : source.id,
                )
              }
            />
          ))
        )}
      </CardContent>
    </Card>
  );
}
