import {
  ratingExplainedSchema,
  type RatingExplained,
} from "@/lib/schemas";
import { cn } from "@/lib/utils";

const intensityColors = {
  mild: "text-emerald-700 bg-emerald-100 border-emerald-200",
  moderate: "text-amber-700 bg-amber-100 border-amber-200",
  strong: "text-red-700 bg-red-100 border-red-200",
};

export function RatingExplainedView({ data }: { data: unknown }) {
  const result = ratingExplainedSchema.safeParse(data);
  if (!result.success) {
    return (
      <div className="rounded-2xl border border-stone-200 bg-white p-6 text-sm text-stone-700">
        Could not display this insight (data format issue). Try another card or refresh later.
      </div>
    );
  }
  const parsed = result.data as RatingExplained;

  return (
    <div className="space-y-5 rounded-2xl border border-stone-200 bg-white p-6">
      <div>
        <p className="text-sm uppercase tracking-wide text-stone-500">
          {parsed.region} rating
        </p>
        <h3 className="mt-1 text-2xl font-semibold text-amber-700">
          {parsed.officialRating}
        </h3>
        <p className="mt-3 text-stone-700">{parsed.summary}</p>
      </div>

      <div className="space-y-3">
        {parsed.factors.map((factor, index) => (
          <div
            key={`${factor.category}-${index}`}
            className="rounded-xl border border-stone-200 bg-stone-100 p-4"
          >
            <div className="mb-2 flex flex-wrap items-center gap-2">
              <span className="text-sm font-medium capitalize text-stone-950">
                {factor.category}
              </span>
              <span
                className={cn(
                  "rounded-full border px-2 py-0.5 text-xs capitalize",
                  intensityColors[factor.intensity],
                )}
              >
                {factor.intensity}
              </span>
              {factor.approximateTiming ? (
                <span className="text-xs text-stone-500">
                  ~{factor.approximateTiming}
                </span>
              ) : null}
            </div>
            <p className="text-sm leading-relaxed text-stone-700">
              {factor.description}
            </p>
          </div>
        ))}
      </div>

      {parsed.borderlineNote ? (
        <p className="rounded-xl border border-amber-400/20 bg-amber-400/5 p-4 text-sm text-amber-100/90">
          {parsed.borderlineNote}
        </p>
      ) : null}
    </div>
  );
}