import { useQuery } from '@tanstack/react-query';
import { apiFetch } from '../lib/api';
import PageScanner from './PageScanner';
import { DashboardSkeleton } from './Skeleton';
import type { PageScanSummary } from '../lib/types';

export default function Dashboard() {
  const { data: pageScans = {}, isLoading } = useQuery({
    queryKey: ['page-scans'],
    queryFn:  () => apiFetch<Record<string, PageScanSummary>>('/page-scans'),
  });

  if (isLoading) return <DashboardSkeleton />;

  // Aggregate issue counts across all scanned pages
  const allIssues = Object.values(pageScans).flatMap((s) => s.issues ?? []);
  const total     = allIssues.length;
  const critical  = allIssues.filter((i) => i.severity === 'critical').length;
  const warning   = allIssues.filter((i) => i.severity === 'warning').length;
  const notice    = allIssues.filter((i) => i.severity === 'notice').length;
  const hasData   = Object.keys(pageScans).length > 0;

  return (
    <div className="aai-dashboard">

      {/* Stats row */}
      {hasData && (
        <>
          <div className="aai-stats-row">
            <StatCard label="Issues found"    value={total}    variant="total"    />
            <StatCard label="Critical issues" value={critical} variant="critical" />
            <StatCard label="Needs attention" value={warning}  variant="warning"  />
            <StatCard label="Notices"         value={notice}   variant="notice"   />
          </div>
          <p className="aai-stats-disclaimer">
            Automated accessibility score based on detected issues.{' '}
            <span title="This score is based on automated checks. Some accessibility issues may require manual testing.">
              Some issues may require manual testing. ⓘ
            </span>
          </p>
          <p className="aai-dashboard-tip">
            💡 Tip: Fix critical issues first for the biggest accessibility impact.
          </p>
        </>
      )}

      {/* Issues by page chart */}
      {hasData && (
        <div className="aai-trend-card">
          <h3 className="aai-pane-title">Issues by Page</h3>
          <p className="aai-chart-sub">Top pages ranked by number of accessibility issues</p>
          <IssuesByPage pageScans={pageScans} />
        </div>
      )}

      {/* Pages & Posts scanner (main dashboard view) */}
      <PageScanner />


    </div>
  );
}

// ── Issues by page bar chart ───────────────────────────────────

function IssuesByPage({ pageScans }: { pageScans: Record<string, PageScanSummary> }) {
  const pages = Object.values(pageScans)
    .filter((s) => s.failed > 0)
    .sort((a, b) => b.failed - a.failed)
    .slice(0, 7);

  if (pages.length === 0) return (
    <p className="aai-chart-empty">No issues detected across scanned pages.</p>
  );

  const maxFailed = pages[0].failed || 1;

  return (
    <div className="aai-ibc">
      {pages.map((scan) => {
        const crit = scan.issues?.filter((i) => i.severity === 'critical').length ?? 0;
        const warn = scan.issues?.filter((i) => i.severity === 'warning').length  ?? 0;
        const note = scan.issues?.filter((i) => i.severity === 'notice').length   ?? 0;
        const pathname = (() => { try { return new URL(scan.url).pathname || '/'; } catch { return scan.url; } })();
        const barPct = (scan.failed / maxFailed) * 100;
        return (
          <div key={scan.url} className="aai-ibc__row">
            <span className="aai-ibc__label" title={scan.url}>{pathname}</span>
            <div className="aai-ibc__track">
              <div className="aai-ibc__bar" style={{ width: `${barPct}%` }}>
                {crit > 0 && <span className="aai-ibc__seg aai-ibc__seg--critical" style={{ flex: crit }} />}
                {warn > 0 && <span className="aai-ibc__seg aai-ibc__seg--warning"  style={{ flex: warn }} />}
                {note > 0 && <span className="aai-ibc__seg aai-ibc__seg--notice"   style={{ flex: note }} />}
              </div>
              <span className="aai-ibc__count">{scan.failed}</span>
            </div>
          </div>
        );
      })}
      <div className="aai-ibc__legend">
        <span><em className="aai-ibc__dot aai-ibc__dot--critical" />Critical</span>
        <span><em className="aai-ibc__dot aai-ibc__dot--warning"  />Warning</span>
        <span><em className="aai-ibc__dot aai-ibc__dot--notice"   />Notice</span>
      </div>
    </div>
  );
}

// ── Stat card ──────────────────────────────────────────────────

function StatCard({ label, value, variant }: { label: string; value: number; variant: string }) {
  return (
    <div className={`aai-stat-card aai-stat-card--${variant}`}>
      <span className="aai-stat-card__value">{value}</span>
      <span className="aai-stat-card__label">{label}</span>
    </div>
  );
}
