import { Star } from "lucide-react";
import type { AppLocale } from "@/lib/i18n/config";
import { td } from "@/lib/i18n/dashboard-labels";
import { Avatar } from "@/components/ui/avatar";
import { Badge } from "@/components/ui/badge";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import type { InputsViewModel } from "@/lib/farmer-dashboard";

type Supplier = NonNullable<InputsViewModel["suppliers"]>[number];

interface SupplierRatingListProps {
  suppliers: Supplier[];
  locale: AppLocale;
}

function StarRating({ rating, locale }: { rating: number; locale: AppLocale }) {
  const fullStars = Math.floor(rating);
  const hasHalf = rating - fullStars >= 0.5;

  return (
    <div
      className="flex items-center gap-0.5"
      aria-label={td("inputsStarRatingAria", locale, { rating: rating.toFixed(1) })}
    >
      {Array.from({ length: 5 }, (_, index) => {
        const filled = index < fullStars || (index === fullStars && hasHalf);
        return (
          <Star
            key={index}
            className={`size-3.5 ${filled ? "fill-warning-amber text-warning-amber" : "text-border"}`}
            aria-hidden="true"
          />
        );
      })}
    </div>
  );
}

export function SupplierRatingList({ suppliers, locale }: SupplierRatingListProps) {
  return (
    <Card data-testid="inputs-supplier-list" padding="md" className="h-full">
      <CardHeader className="mb-0 flex flex-row items-center justify-between gap-2">
        <CardTitle className="text-base">{td("inputsSuppliersTitle", locale)}</CardTitle>
        <button
          type="button"
          className="font-inter text-xs font-medium text-brand-green hover:underline focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-green-deep focus-visible:ring-offset-2"
        >
          {td("inputsViewAll", locale)}
        </button>
      </CardHeader>
      <CardContent className="mt-4 space-y-3">
        {suppliers.map((supplier) => (
          <div
            key={supplier.name}
            data-testid={`inputs-supplier-${supplier.name.replace(/\s+/g, "-").toLowerCase()}`}
            className="flex items-center gap-3 rounded-xl border border-border bg-surface p-3"
          >
            <Avatar
              src={supplier.logoUrl}
              alt={supplier.name}
              size="sm"
            />
            <div className="min-w-0 flex-1">
              <p className="truncate font-inter text-sm font-medium text-ink">
                {supplier.name}
              </p>
              <StarRating rating={supplier.rating} locale={locale} />
            </div>
            <Badge variant="success" icon={false} className="shrink-0">
              {supplier.rating.toFixed(1)}
            </Badge>
          </div>
        ))}
      </CardContent>
    </Card>
  );
}
