import { useState } from 'react';
import { useQuery } from '@tanstack/react-query';
import { useReport } from '../hooks/useReport';
import { useAI } from '../hooks/useAI';
import { apiFetch } from '../lib/api';
import { markdownToHtml } from '../lib/markdown';
import ScanSlideIn from './ScanSlideIn';
import { ReportSkeleton } from './Skeleton';
import type { PageScanSummary } from '../lib/types';

// ── Helpers ───────────────────────────────────────────────────

function scoreColor(s: number) {
  return s >= 90 ? '#22c55e' : s >= 75 ? '#84cc16' : s >= 55 ? '#f59e0b' : s >= 35 ? '#f97316' : '#ef4444';
}


function exportCsv(pageScans: Record<string, PageScanSummary>) {
  const cols = ['Page URL', 'WCAG', 'Severity', 'Issue Title', 'Description', 'Selector', 'Elements'];
  const esc  = (v: string) => `"${String(v ?? '').replace(/"/g, '""')}"`;
  const lines = [cols.map(esc).join(',')];
  Object.values(pageScans).forEach((scan) => {
    (scan.issues ?? []).forEach((iss) => {
      lines.push([
        scan.url, iss.wcag ?? '', iss.severity, iss.title,
        iss.description, iss.selector ?? '', iss.count,
      ].map(String).map(esc).join(','));
    });
  });
  const blob = new Blob([lines.join('\n')], { type: 'text/csv' });
  const a    = document.createElement('a');
  a.href     = URL.createObjectURL(blob);
  a.download = `accessibility-audit-${new Date().toISOString().slice(0, 10)}.csv`;
  a.click();
  URL.revokeObjectURL(a.href);
}


// ── Summary bar ───────────────────────────────────────────────

function SummaryBar({ pageScans }: { pageScans: Record<string, PageScanSummary> }) {
  const all      = Object.values(pageScans).flatMap((s) => s.issues ?? []);
  const critical = all.filter((i) => i.severity === 'critical').length;
  const warning  = all.filter((i) => i.severity === 'warning').length;
  const notice   = all.filter((i) => i.severity === 'notice').length;
  const pages    = Object.keys(pageScans).length;

  return (
    <div className="aai-audit-summary">
      <div className="aai-audit-summary-stat">
        <span className="aai-audit-summary-val">{all.length}</span>
        <span className="aai-audit-summary-lbl">Issues found</span>
      </div>
      <div className="aai-audit-summary-stat">
        <span className="aai-audit-summary-val" style={{ color: '#ef4444' }}>{critical}</span>
        <span className="aai-audit-summary-lbl">Critical issues</span>
      </div>
      <div className="aai-audit-summary-stat">
        <span className="aai-audit-summary-val" style={{ color: '#f59e0b' }}>{warning}</span>
        <span className="aai-audit-summary-lbl">Needs attention</span>
      </div>
      <div className="aai-audit-summary-stat">
        <span className="aai-audit-summary-val" style={{ color: '#3b82f6' }}>{notice}</span>
        <span className="aai-audit-summary-lbl">Notices</span>
      </div>
      <div className="aai-audit-summary-stat">
        <span className="aai-audit-summary-val">{pages}</span>
        <span className="aai-audit-summary-lbl">Pages Scanned</span>
      </div>
    </div>
  );
}

// ── Main report view ──────────────────────────────────────────

export default function ReportView() {
  const { data: report }  = useReport();
  const { run, hasProvider } = useAI();
  const [summary, setSummary]         = useState<string | null>(null);
  const [aiError, setAiError]         = useState<string | null>(null);
  const [searchInput, setSearchInput] = useState('');
  const [search, setSearch]           = useState('');
  const [selectedScan, setSelectedScan] = useState<PageScanSummary | null>(null);

  const { data: pageScans = {}, isLoading: scansLoading } = useQuery({
    queryKey: ['page-scans', search],
    queryFn:  () => apiFetch<Record<string, PageScanSummary>>(search ? `/page-scans?search=${encodeURIComponent(search)}` : '/page-scans'),
  });

  if (scansLoading) return <ReportSkeleton />;

  if (Object.keys(pageScans).length === 0 && !search) {
    return (
      <div className="aai-empty">
        <p className="aai-empty__primary">No issues detected</p>
        <p className="aai-empty__sub">This scan didn't detect any accessibility issues. Some issues may require manual testing with assistive technologies.</p>
      </div>
    );
  }

  const allScans     = Object.values(pageScans).sort((a, b) => b.failed - a.failed);
  const displayScans = allScans;

  const generateSummary = async () => {
    setSummary(null); setAiError(null);
    const allIssues = allScans.flatMap((s) => s.issues ?? []);
    const critical  = allIssues.filter((i) => i.severity === 'critical').length;
    const warnings  = allIssues.filter((i) => i.severity === 'warning').length;
    try {
      const result = await run.mutateAsync({
        task: 'report',
        params: { score: String(report?.score ?? 0), critical: String(critical), warnings: String(warnings) },
      });
      if (result.error) setAiError(result.error);
      else setSummary(result.text ?? '');
    } catch (e) { setAiError((e as Error).message); }
  };

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

      {/* Page issues slide-in */}
      <ScanSlideIn scan={selectedScan} onClose={() => setSelectedScan(null)} />

      {/* ── Header ── */}
      <div className="aai-audit-header">
        <div className="aai-audit-header-left">
          <h2 className="aai-audit-title">Accessibility Audit Report</h2>
          {report?.scanned_at && (
            <span className="aai-audit-date">
              {new Date(report.scanned_at).toLocaleDateString(undefined, { year: 'numeric', month: 'long', day: 'numeric' })}
            </span>
          )}
        </div>
      </div>

      {/* ── Automated scan disclaimer ── */}
      <div className="aai-audit-notice">
        This report highlights issues detected through automated scanning. Some accessibility issues may require manual testing for full WCAG 2.1 AA compliance.
      </div>

      {/* ── WCAG Standard notice ── */}
      <div className="aai-audit-standard">
        <span>Standard: <strong>WCAG 2.1 Level AA</strong></span>
        <span>Engine: <strong>axe-core 4.x</strong></span>
        <span>Scope: <strong>Browser-based automated scan</strong></span>
      </div>

      {/* ── Summary bar ── */}
      <SummaryBar pageScans={pageScans} />

      {/* ── AI summary ── */}
      {summary && (
        <div className="aai-audit-ai-summary">
          <strong>AI Compliance Summary</strong>
          <div className="aai-audit-ai-md" dangerouslySetInnerHTML={{ __html: markdownToHtml(summary) }} />
        </div>
      )}
      {aiError && <p className="aai-error" style={{ marginBottom: 12 }}>{aiError}</p>}

      {/* ── Toolbar ── */}
      <div className="aai-audit-toolbar">
        <div className="aai-audit-filters">
          <div className="aai-ps-search-wrap">
            <svg className="aai-ps-search-icon" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 20 20" fill="none" aria-hidden="true"><circle cx="8.5" cy="8.5" r="5.5" stroke="currentColor" strokeWidth="1.6"/><path d="M13 13l3.5 3.5" stroke="currentColor" strokeWidth="1.6" strokeLinecap="round"/></svg>
            <input
              type="search"
              placeholder="Search pages… (press Enter)"
              className="aai-ps-search"
              value={searchInput}
              onChange={(e) => setSearchInput(e.target.value)}
              onKeyDown={(e) => { if (e.key === 'Enter') { setSearch(searchInput.trim()); } }}
              aria-label="Search pages"
            />
            {searchInput && (
              <button className="aai-ps-search-clear" onClick={() => { setSearchInput(''); setSearch(''); }} aria-label="Clear search">✕</button>
            )}
          </div>
        </div>
        <div className="aai-audit-toolbar-right">
          <button
            className="aai-btn aai-btn--secondary aai-btn--sm"
            onClick={generateSummary}
            disabled={!hasProvider || run.isPending}
            title={!hasProvider ? 'Configure an AI provider in Settings' : undefined}
          >
            {run.isPending ? <><span className="aai-spinner" aria-hidden="true" /> Generating…</> : 'AI Summary'}
          </button>
        </div>
      </div>

      {/* ── Pages table ── */}
      {displayScans.length === 0 ? (
        <div className="aai-empty" style={{ marginTop: 16 }}>
          <p>No pages match your search.</p>
        </div>
      ) : (
        <div className="aai-audit-table-wrap">
          <table className="aai-audit-table">
            <thead>
              <tr>
                <th className="aai-audit-th aai-audit-th--num">#</th>
                <th className="aai-audit-th">Page URL</th>
                <th className="aai-audit-th">Grade</th>
                <th className="aai-audit-th">Score</th>
                <th className="aai-audit-th">Issues</th>
                <th className="aai-audit-th">Last Scanned</th>
                <th className="aai-audit-th"></th>
              </tr>
            </thead>
            <tbody>
              {displayScans.map((scan, i) => {
                const c = scoreColor(scan.score);
                return (
                  <tr key={scan.url} className="aai-audit-row" style={{ borderLeft: `3px solid ${c}` }}>
                    <td className="aai-audit-td aai-audit-td--num">{i + 1}</td>
                    <td className="aai-audit-td">
                      <a
                        href={scan.url} target="_blank" rel="noopener noreferrer"
                        className="aai-audit-link" title={scan.url}
                      >
                        {(() => { try { return new URL(scan.url).pathname || '/'; } catch { return scan.url; } })()}
                      </a>
                      <span className="aai-audit-page-url">{scan.url}</span>
                    </td>
                    <td className="aai-audit-td">
                      <span className="aai-audit-badge" style={{ background: c + '22', color: c, border: `1px solid ${c}55` }}>
                        {scan.grade}
                      </span>
                    </td>
                    <td className="aai-audit-td" style={{ color: c, fontWeight: 600 }}>{scan.score}</td>
                    <td className="aai-audit-td" style={{ color: scan.failed > 0 ? '#ef4444' : '#22c55e', fontWeight: 600 }}>
                      {scan.failed}
                    </td>
                    <td className="aai-audit-td aai-muted" style={{ fontSize: 12, whiteSpace: 'nowrap' }}>
                      {new Date(scan.scanned_at).toLocaleString(undefined, {
                        month: 'short', day: 'numeric', hour: '2-digit', minute: '2-digit',
                      })}
                    </td>
                    <td className="aai-audit-td">
                      <button
                        className="aai-btn aai-btn--sm aai-btn--ghost"
                        onClick={() => setSelectedScan(scan)}
                      >
                        View
                      </button>
                    </td>
                  </tr>
                );
              })}
            </tbody>
          </table>
        </div>
      )}


      <p className="aai-audit-footer-note">
        AccessMate uses automated scanning to identify and help fix accessibility issues. Automated tools can detect only a subset of accessibility problems. For full WCAG 2.1 AA compliance, manual testing — including testing with assistive technologies such as screen readers — is recommended.
      </p>
      <p className="aai-audit-footer-note" style={{ marginTop: 6 }}>
        AccessMate helps you find and fix accessibility issues faster. It does not replace a full manual accessibility audit.
      </p>
    </div>
  );
}
