import React, { useEffect, useState } from 'react';
import { FiCheckCircle, FiList, FiXCircle } from 'react-icons/fi';

import InfoTooltip from '../agent-analytics/InfoTooltip';
import type {
  AeoCheck,
  ArticleAeoChecklistResponse,
} from '../../service/visibility/visibility.interface';
import { getArticleAeoChecklist } from '../../service/visibility/visibility.service';

import { scoreTextColor } from './helpers';

interface AeoChecklistPanelProps {
  clientId: string;
  token: string;
  articleId: string;
}

/** Display label + optional unit for each AEO signal key. */
const CHECK_META: Record<string, { label: string; unit?: string }> = {
  answer_first: { label: 'Answer-first sections', unit: '%' },
  structured_headings: { label: 'Structured headings' },
  comparison_table: { label: 'Comparison table' },
  lists: { label: 'Bulleted / numbered lists' },
  short_paragraphs: { label: 'Short paragraphs' },
  faq: { label: 'FAQ block' },
  article_schema: { label: 'Article schema (JSON-LD)' },
  faq_schema: { label: 'FAQ schema (JSON-LD)' },
  title_length: { label: 'Concise title', unit: ' chars' },
  meta_description: { label: 'Meta description', unit: ' chars' },
  internal_links: { label: 'Internal links' },
  external_references: { label: 'Authoritative references' },
  freshness: { label: 'Freshness', unit: 'd' },
};

/** One signal row: pass/fail glyph, label, and the measured value. */
function CheckRow({ check }: { check: AeoCheck }): JSX.Element {
  const meta = CHECK_META[check.key] ?? { label: check.key };
  const value =
    check.value !== null && check.value !== undefined
      ? `${check.value}${meta.unit ?? ''}`
      : null;

  return (
    <div className="flex items-center justify-between gap-2 border-t border-gray-200 py-1 first:border-t-0">
      <div className="flex items-center gap-2">
        {check.passed ? (
          <FiCheckCircle className="h-4 w-4 flex-shrink-0 text-green-600" />
        ) : (
          <FiXCircle className="h-4 w-4 flex-shrink-0 text-red-600" />
        )}
        <span
          className={`text-sm ${check.passed ? 'text-gray-900' : 'text-gray-500'}`}
        >
          {meta.label}
        </span>
      </div>
      {value !== null && <span className="text-xs text-gray-500">{value}</span>}
    </div>
  );
}

/** Coloured score number, e.g. "SEO 98". */
function ScoreStat({
  label,
  score,
  tooltip,
}: {
  label: string;
  score: number;
  tooltip?: string;
}): JSX.Element {
  return (
    <span className="inline-flex items-center gap-1">
      {label}{' '}
      <span className={`font-medium ${scoreTextColor(score)}`}>{score}</span>
      {tooltip && <InfoTooltip text={tooltip} />}
    </span>
  );
}

/**
 * Article AEO checklist (Beta): the AI-extraction signals an article has vs is
 * missing, plus the composite AEO / SEO / Quality / Google-compliance scores.
 * Fetches client-side so it never blocks the article render.
 */
export function AeoChecklistPanel({
  clientId,
  token,
  articleId,
}: AeoChecklistPanelProps): JSX.Element | null {
  const [data, setData] = useState<ArticleAeoChecklistResponse | null>(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);

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

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

  // Nothing to show yet: stay silent rather than render an empty card.
  if (!loading && !error && !data) return null;

  const passed = data ? data.checks.filter(check => check.passed).length : 0;
  const total = data ? data.checks.length : 0;

  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 flex-wrap items-center justify-between gap-2">
          <div className="flex items-center gap-2">
            <FiList className="h-4 w-4 text-yellow-600" />
            <h3 className="text-base font-semibold text-gray-900">
              AEO checklist
            </h3>
            <span className="inline-flex items-center rounded-full border border-orange-200 bg-orange-100 px-2 py-0.5 text-[11px] font-medium text-orange-800">
              Beta
            </span>
            <InfoTooltip text="Answer Engine Optimization: the structural signals AI engines use to extract and cite a page. Each item is a concrete, fixable lever; the more you pass, the more quotable your article is to ChatGPT, Gemini, and AI Overviews." />
          </div>
          {data && (
            <span className="text-xs text-gray-500">
              AEO score{' '}
              <span
                className={`text-base font-bold ${scoreTextColor(data.aeo_score)}`}
              >
                {data.aeo_score}
              </span>
              /100
            </span>
          )}
        </div>
        <p className="text-xs text-gray-500">
          How extractable this article is for AI answers. Fix the red items to
          earn more citations.
        </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 && (
        <>
          <div className="flex flex-wrap gap-x-4 gap-y-1 text-xs text-gray-500">
            <span>
              <span className="font-medium text-gray-900">
                {`${passed}/${total}`}
              </span>{' '}
              signals passing
            </span>
            <ScoreStat label="SEO" score={data.seo_score} />
            <ScoreStat label="Quality" score={data.quality_score} />
            <ScoreStat
              label="Google compliance"
              score={data.compliance_score}
              tooltip="How well this article follows Google's latest content guidance: people-first and data-backed, original (no templated boilerplate or keyword stuffing), authoritative references, and structured data."
            />
          </div>
          <div>
            {data.checks.map(check => (
              <CheckRow key={check.key} check={check} />
            ))}
          </div>
        </>
      )}
    </div>
  );
}

export default AeoChecklistPanel;
