import React, { useEffect, useState } from 'react';
import { FiChevronDown, FiChevronUp, FiLink } from 'react-icons/fi';

import InfoTooltip from '../agent-analytics/InfoTooltip';
import type {
  CitationAuthorityTier,
  CitedSourceEntry,
  CitedSourcesResponse,
} from '../../service/visibility/visibility.interface';
import { getCitedSources } from '../../service/visibility/visibility.service';

import { toneToBadgeClass } from './helpers';

interface CitedSourcesPanelProps {
  clientId: string;
  token: string;
  brandId: string;
}

/** Sources listed before the "Show all" toggle reveals the rest. */
const SOURCES_COLLAPSED = 8;

const TIER_TONE: Record<CitationAuthorityTier, 'success' | 'info' | undefined> =
  {
    top: 'success',
    mid: 'info',
    low: undefined,
    unknown: undefined,
  };

const TIER_LABEL: Record<CitationAuthorityTier, string> = {
  top: 'Top authority',
  mid: 'Mid authority',
  low: 'Low authority',
  unknown: 'Unrated',
};

/** One cited-source row: domain, authority tier, citation count, brand flags. */
function SourceRow({ source }: { source: CitedSourceEntry }): JSX.Element {
  return (
    <div className="flex items-center justify-between gap-2 border-t border-gray-200 py-1.5 first:border-t-0">
      <div className="flex min-w-0 items-center gap-2">
        <span className="truncate text-sm text-gray-900">{source.domain}</span>
        {source.is_owned && (
          <span
            className={`inline-flex items-center rounded-full px-2 py-0.5 text-[11px] font-medium ${toneToBadgeClass('info')}`}
          >
            Your site
          </span>
        )}
        {source.cites_brand && !source.is_owned && (
          <span
            className={`inline-flex items-center rounded-full px-2 py-0.5 text-[11px] font-medium ${toneToBadgeClass('success')}`}
          >
            Cites you
          </span>
        )}
      </div>
      <div className="flex flex-shrink-0 items-center gap-2">
        <span
          className={`inline-flex items-center rounded-full px-2 py-0.5 text-[11px] font-medium ${toneToBadgeClass(TIER_TONE[source.authority_tier])}`}
        >
          {TIER_LABEL[source.authority_tier]}
        </span>
        <span className="w-11 text-right text-xs text-gray-500">
          {`${source.total_citations_30d}×`}
        </span>
      </div>
    </div>
  );
}

/**
 * Cited-sources panel (Beta): the domains AI search cites in the brand's
 * category plus the competitors it's co-cited alongside. Collapsed to the top
 * sources with a "Show all" toggle. Fetches client-side.
 */
const CitedSourcesPanel = ({
  clientId,
  token,
  brandId,
}: CitedSourcesPanelProps): JSX.Element | null => {
  const [data, setData] = useState<CitedSourcesResponse | null>(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);
  const [expanded, setExpanded] = useState(false);

  useEffect(() => {
    let cancelled = false;
    setLoading(true);
    setError(null);
    getCitedSources(clientId, token, brandId)
      .then(result => {
        if (!cancelled) setData(result);
      })
      .catch(err => {
        if (!cancelled)
          setError(
            err instanceof Error ? err.message : 'Failed to load cited sources.'
          );
      })
      .finally(() => {
        if (!cancelled) setLoading(false);
      });

    return () => {
      cancelled = true;
    };
  }, [clientId, token, brandId]);

  // Nothing scanned yet: stay silent rather than render an empty card.
  if (!loading && !error && (!data || data.sources.length === 0)) {
    return null;
  }

  const loaded = data?.sources ?? [];
  const shown = expanded ? loaded : loaded.slice(0, SOURCES_COLLAPSED);
  const canExpand = loaded.length > SOURCES_COLLAPSED;
  // Backend caps the payload at the top 50; surface the long tail as a count.
  const beyondLoaded = (data?.total_sources ?? 0) - loaded.length;

  return (
    <div className="flex flex-col gap-4 rounded-xl border border-gray-200 bg-white p-5">
      <div className="flex flex-col gap-1">
        <div className="flex items-center gap-2">
          <FiLink className="h-4 w-4 text-yellow-600" />
          <h3 className="text-base font-semibold text-gray-900">
            Cited sources
          </h3>
          <span
            className={`inline-flex items-center rounded-full px-2 py-0.5 text-[11px] font-medium ${toneToBadgeClass('attention')}`}
          >
            Beta
          </span>
          <InfoTooltip text="The websites AI engines pull from when answering questions in your category. Getting mentioned on the high-authority ones (and the ones already citing rivals) is how you earn citations. Co-citation shows the competitors you share those sources with." />
        </div>
        <p className="text-xs text-gray-500">
          Where AI answers in your category get their facts. Earn a mention on
          these to get cited too.
        </p>
      </div>

      {loading && (
        <div className="animate-pulse space-y-2">
          <div className="h-4 w-1/2 rounded bg-gray-200" />
          <div className="h-4 w-2/3 rounded bg-gray-200" />
          <div className="h-4 w-1/3 rounded bg-gray-200" />
        </div>
      )}

      {error && <p className="text-sm text-red-700">{error}</p>}

      {!loading && !error && data && data.sources.length > 0 && (
        <>
          <div className="flex flex-wrap gap-x-4 gap-y-1 text-xs text-gray-500">
            <span>
              <span className="font-medium text-gray-900">
                {data.total_sources}
              </span>{' '}
              sources
            </span>
            <span>
              <span className="font-medium text-gray-900">
                {data.brand_cited_sources}
              </span>{' '}
              cite you
            </span>
            <span>
              <span className="font-medium text-gray-900">
                {`${data.top_tier_share}%`}
              </span>{' '}
              top authority
            </span>
          </div>

          <div>
            {shown.map(source => (
              <SourceRow key={source.domain} source={source} />
            ))}
          </div>

          {(canExpand || beyondLoaded > 0) && (
            <div className="flex items-center justify-between gap-2">
              {canExpand ? (
                <button
                  type="button"
                  onClick={() => setExpanded(value => !value)}
                  className="inline-flex items-center gap-1 text-xs font-medium text-gray-900 hover:underline"
                >
                  {expanded ? (
                    <>
                      <FiChevronUp className="h-3.5 w-3.5" /> Show fewer
                    </>
                  ) : (
                    <>
                      <FiChevronDown className="h-3.5 w-3.5" /> Show all{' '}
                      {loaded.length}
                    </>
                  )}
                </button>
              ) : (
                <span />
              )}
              {beyondLoaded > 0 && (
                <span className="text-[11px] text-gray-500">
                  {`+${beyondLoaded} more in the long tail`}
                </span>
              )}
            </div>
          )}

          {data.co_citation.length > 0 && (
            <div className="flex flex-col gap-2 border-t border-gray-200 pt-3">
              <div className="flex items-center gap-1">
                <p className="text-xs font-medium text-gray-900">
                  You&apos;re cited alongside
                </p>
                <InfoTooltip text="Competitors that appear on the same sources that cite you. These are the rivals you're directly compared with inside AI answers." />
              </div>
              <div className="flex flex-wrap gap-1.5">
                {data.co_citation.map(neighbor => (
                  <span
                    key={neighbor.competitor_domain}
                    className="rounded-md bg-gray-100 px-2 py-0.5 text-[11px] text-gray-500"
                  >
                    {neighbor.competitor_domain}
                    <span className="ml-1 text-gray-900">
                      {neighbor.shared_sources}
                    </span>
                  </span>
                ))}
              </div>
            </div>
          )}
        </>
      )}
    </div>
  );
};

export default CitedSourcesPanel;
