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

const intensityColors = {
  mild: "text-emerald-300 bg-emerald-400/10 border-emerald-400/20",
  moderate: "text-amber-300 bg-amber-400/10 border-amber-400/20",
  strong: "text-red-300 bg-red-400/10 border-red-400/20",
};

export function RatingExplainedView({ data }: { data: unknown }) {
  const result = ratingExplainedSchema.safeParse(data);
  if (!result.success) {
    return (
      <div className="rounded-2xl border border-white/10 bg-white/[0.03] p-6 text-sm text-slate-400">
        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-white/10 bg-white/[0.03] p-6">
      <div>
        <p className="text-sm uppercase tracking-wide text-slate-500">
          {parsed.region} rating
        </p>
        <h3 className="mt-1 text-2xl font-semibold text-amber-200">
          {parsed.officialRating}
        </h3>
        <p className="mt-3 text-slate-300">{parsed.summary}</p>
      </div>

      <div className="space-y-3">
        {parsed.factors.map((factor, index) => (
          <div
            key={`${factor.category}-${index}`}
            className="rounded-xl border border-white/10 bg-slate-950/40 p-4"
          >
            <div className="mb-2 flex flex-wrap items-center gap-2">
              <span className="text-sm font-medium capitalize text-white">
                {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-slate-500">
                  ~{factor.approximateTiming}
                </span>
              ) : null}
            </div>
            <p className="text-sm leading-relaxed text-slate-300">
              {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>
  );
}