import React from 'react';

import { CardSkeleton } from '../agent-analytics/CardSkeleton';
import InfoTooltip from '../agent-analytics/InfoTooltip';

import { formatDelta, toneToBadgeClass } from './helpers';

const EXPLANATIONS = {
  visibility:
    'Blended 0–100 score combining share of voice, citation rate from your own domain, and your average position in AI answers across the 16 monitored prompts.',
  sov: 'Share of Voice - the percentage of brand mentions your domain captured among all brands surfaced by AI answers for the tracked prompts this week.',
  rank: "Your brand's overall rank among all entities that appeared in this week's AI responses - lower is better. '#3 of 18' means three brands scored above you.",
  sentiment:
    'How AI described your brand this week. Positive / negative percentages reflect the tone of every response that mentioned you; anything not clearly positive or negative is counted as neutral.',
};

interface KPIRowProps {
  visibilityScore: number;
  shareOfVoice: number;
  brandRank: number | null;
  totalCompetingEntities: number | null;
  deltaScore: number | null;
  deltaSov: number | null;
  sentimentPositivePct: number | null;
  sentimentNegativePct: number | null;
  deltaSentiment: number | null;
  loading: boolean;
}

/**
 * 4-card KPI row: Visibility score, Share of voice, Rank #X of Y, Sentiment.
 * Each card's "vs last week" row is hidden when its delta is ``null`` (first
 * week); ``0`` is treated as "no change".
 */
const KPIRow = ({
  visibilityScore,
  shareOfVoice,
  brandRank,
  totalCompetingEntities,
  deltaScore,
  deltaSov,
  sentimentPositivePct,
  sentimentNegativePct,
  deltaSentiment,
  loading,
}: KPIRowProps): JSX.Element => {
  if (loading) {
    return (
      <div className="grid grid-cols-1 sm:grid-cols-2 md:grid-cols-4 gap-4">
        <CardSkeleton />
        <CardSkeleton />
        <CardSkeleton />
        <CardSkeleton />
      </div>
    );
  }

  const visibilityDelta = formatDelta(deltaScore, ' pts');
  const sovDelta = formatDelta(deltaSov, '%');
  const sentimentDelta = formatDelta(deltaSentiment, '%');
  const rankLabel =
    brandRank !== null && totalCompetingEntities !== null
      ? `#${brandRank} of ${totalCompetingEntities}`
      : brandRank !== null
        ? `#${brandRank}`
        : '-';

  const clampPct = (v: number | null): number => {
    if (v === null || !Number.isFinite(v)) return 0;
    if (v < 0) return 0;
    if (v > 100) return 100;

    return v;
  };
  const positivePct = clampPct(sentimentPositivePct);
  const negativePct = clampPct(sentimentNegativePct);
  const hasSentiment =
    sentimentPositivePct !== null || sentimentNegativePct !== null;

  return (
    <div className="grid grid-cols-1 sm:grid-cols-2 md:grid-cols-4 gap-4">
      {/* Visibility score */}
      <div className="bg-white rounded-xl border border-gray-200 p-4 flex flex-col gap-2">
        <div className="flex items-center gap-1">
          <span className="text-xs text-gray-500">Visibility score</span>
          <InfoTooltip text={EXPLANATIONS.visibility} />
        </div>
        <p className="text-xl font-bold text-gray-900">
          {visibilityScore}
          <span className="text-xs font-normal text-gray-500"> / 100</span>
        </p>
        {!visibilityDelta.hidden && (
          <div className="flex items-center gap-2">
            <span
              className={`inline-flex items-center rounded-full px-2.5 py-0.5 text-xs font-medium ${toneToBadgeClass(visibilityDelta.tone)}`}
            >
              {visibilityDelta.label}
            </span>
            <span className="text-xs text-gray-500">vs last week</span>
          </div>
        )}
      </div>

      {/* Share of voice */}
      <div className="bg-white rounded-xl border border-gray-200 p-4 flex flex-col gap-2">
        <div className="flex items-center gap-1">
          <span className="text-xs text-gray-500">Share of voice</span>
          <InfoTooltip text={EXPLANATIONS.sov} />
        </div>
        <p className="text-xl font-bold text-gray-900">
          {shareOfVoice}
          <span className="text-xs font-normal text-gray-500"> %</span>
        </p>
        {!sovDelta.hidden && (
          <div className="flex items-center gap-2">
            <span
              className={`inline-flex items-center rounded-full px-2.5 py-0.5 text-xs font-medium ${toneToBadgeClass(sovDelta.tone)}`}
            >
              {sovDelta.label}
            </span>
            <span className="text-xs text-gray-500">vs last week</span>
          </div>
        )}
      </div>

      {/* Rank */}
      <div className="bg-white rounded-xl border border-gray-200 p-4 flex flex-col gap-2">
        <div className="flex items-center gap-1">
          <span className="text-xs text-gray-500">Rank</span>
          <InfoTooltip text={EXPLANATIONS.rank} />
        </div>
        <p className="text-xl font-bold text-gray-900">{rankLabel}</p>
      </div>

      {/* Sentiment */}
      <div className="bg-white rounded-xl border border-gray-200 p-4 flex flex-col gap-2">
        <div className="flex items-center gap-1">
          <span className="text-xs text-gray-500">Sentiment</span>
          <InfoTooltip text={EXPLANATIONS.sentiment} />
        </div>
        {hasSentiment ? (
          <div className="flex flex-col gap-2">
            <div className="flex flex-col gap-1">
              <div className="flex items-center justify-between">
                <span className="text-xs text-gray-700">Positive</span>
                <span className="text-xs font-semibold text-gray-900">
                  {`${positivePct}%`}
                </span>
              </div>
              <div
                className="h-2 w-full rounded bg-green-100 overflow-hidden"
                aria-hidden="true"
              >
                <div
                  className="h-full bg-green-700 transition-all"
                  style={{ width: `${positivePct}%` }}
                />
              </div>
            </div>
            <div className="flex flex-col gap-1">
              <div className="flex items-center justify-between">
                <span className="text-xs text-gray-700">Negative</span>
                <span className="text-xs font-semibold text-gray-900">
                  {`${negativePct}%`}
                </span>
              </div>
              <div
                className="h-2 w-full rounded bg-red-100 overflow-hidden"
                aria-hidden="true"
              >
                <div
                  className="h-full bg-red-600 transition-all"
                  style={{ width: `${negativePct}%` }}
                />
              </div>
            </div>
            {!sentimentDelta.hidden && (
              <div className="flex items-center gap-2">
                <span
                  className={`inline-flex items-center rounded-full px-2.5 py-0.5 text-xs font-medium ${toneToBadgeClass(sentimentDelta.tone)}`}
                >
                  {sentimentDelta.label}
                </span>
                <span className="text-xs text-gray-500">vs last week</span>
              </div>
            )}
          </div>
        ) : (
          <p className="text-xs text-gray-500">
            No sentiment data for this period.
          </p>
        )}
      </div>
    </div>
  );
};

export default KPIRow;
