import { useEffect, useState } from 'react';
import { useAI } from '../hooks/useAI';
import { markdownToHtml } from '../lib/markdown';
import type { Issue, PageScanSummary } from '../lib/types';

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

interface Props {
  scan:    PageScanSummary | null;
  onClose: () => void;
}

export default function ScanSlideIn({ scan, onClose }: Props) {
  const { run, hasProvider } = useAI();
  const [filter, setFilter]           = useState<'all' | 'critical' | 'warning' | 'notice'>('all');
  const [detailIssue, setDetailIssue] = useState<Issue | null>(null);
  const [visible, setVisible]         = useState(false);
  const [aiOutput, setAiOutput]       = useState<string | null>(null);
  const [aiError, setAiError]         = useState<string | null>(null);
  const [activeAction, setActiveAction] = useState<string | null>(null);
  const [openNodeIdx, setOpenNodeIdx] = useState<number>(0);

  // Animate in when scan arrives; reset state when scan changes
  useEffect(() => {
    if (scan) {
      setFilter('all');
      setDetailIssue(null);
      requestAnimationFrame(() => setVisible(true));
    } else {
      setVisible(false);
    }
  }, [scan]);

  // Reset AI + accordion when switching issues
  useEffect(() => {
    setAiOutput(null);
    setAiError(null);
    setActiveAction(null);
    setOpenNodeIdx(0);
  }, [detailIssue?.id]);

  // Escape key: close detail → then close panel
  useEffect(() => {
    if (!scan) return;
    const handler = (e: KeyboardEvent) => {
      if (e.key !== 'Escape') return;
      if (detailIssue) setDetailIssue(null);
      else onClose();
    };
    document.addEventListener('keydown', handler);
    return () => document.removeEventListener('keydown', handler);
  }, [scan, onClose, detailIssue]);

  const callAI = async (task: string) => {
    if (!detailIssue) return;
    setAiOutput(null);
    setAiError(null);
    setActiveAction(task);
    try {
      const result = await run.mutateAsync({
        task,
        params: {
          title:   detailIssue.title,
          wcag:    detailIssue.wcag ?? '',
          html:    detailIssue.element ?? '',
          context: detailIssue.description,
        },
      });
      if (result.error) setAiError(result.error);
      else              setAiOutput(result.text ?? '');
    } catch (e) {
      setAiError((e as Error).message);
    } finally {
      setActiveAction(null);
    }
  };

  if (!scan) return null;

  const issues   = scan.issues ?? [];
  const filtered = filter === 'all' ? issues : issues.filter((i) => i.severity === filter);
  const critical = issues.filter((i) => i.severity === 'critical').length;
  const warning  = issues.filter((i) => i.severity === 'warning').length;
  const notice   = issues.filter((i) => i.severity === 'notice').length;
  const color    = scoreColor(scan.score);
  const showDetail = detailIssue !== null;
  const sevColor = detailIssue
    ? detailIssue.severity === 'critical' ? '#ef4444'
    : detailIssue.severity === 'warning'  ? '#f59e0b' : '#3b82f6'
    : '#3b82f6';

  return (
    <>
      {/* Backdrop */}
      <div
        className={`ssi-backdrop${visible ? ' ssi-backdrop--visible' : ''}`}
        onClick={onClose}
        role="presentation"
        aria-hidden="true"
      />

      {/* Panel */}
      <div
        className={`ssi-panel${visible ? ' ssi-panel--open' : ''}`}
        role="dialog"
        aria-label="Scan results"
        aria-modal="true"
      >
        {/* Header */}
        <div className="ssi-hd">
          <div className="ssi-hd__left">
            <span className="ssi-hd__title">Scan Results</span>
            <span className="ssi-hd__url" title={scan.url}>{scan.url}</span>
          </div>
          <button className="ssi-hd__close" onClick={onClose} aria-label="Close panel">×</button>
        </div>

        {/* Sliding views container */}
        <div className="ssi-views">

          {/* ── List view ── */}
          <div className={`ssi-list-view${showDetail ? ' ssi-list-view--out' : ''}`}>
            {/* Score row */}
            <div className="ssi-score">
              <div className="ssi-score__grade" style={{ background: color }}>{scan.grade}</div>
              <div>
                <div className="ssi-score__val">{scan.score}<small>/100</small></div>
                <div className="ssi-score__sub">
                  {scan.failed} issue{scan.failed !== 1 ? 's' : ''} detected &middot;{' '}
                  {new Date(scan.scanned_at).toLocaleString(undefined, {
                    month: 'short', day: 'numeric', hour: '2-digit', minute: '2-digit',
                  })}
                </div>
              </div>
            </div>

            {/* Filter tabs */}
            {issues.length > 0 && (
              <div className="ssi-filters">
                {(['all', 'critical', 'warning', 'notice'] as const).map((f) => {
                  const count = f === 'all' ? issues.length : f === 'critical' ? critical : f === 'warning' ? warning : notice;
                  if (f !== 'all' && count === 0) return null;
                  return (
                    <button
                      key={f}
                      className={`ps-filter-btn${filter === f ? ' ps-filter-btn--active' : ''}`}
                      onClick={() => setFilter(f)}
                    >
                      {f.charAt(0).toUpperCase() + f.slice(1)} ({count})
                    </button>
                  );
                })}
              </div>
            )}

            {/* Issue list */}
            <div className="ssi-body">
              {issues.length === 0 ? (
                <div className="ps-panel__empty">
                  <p>✓ No issues detected in this scan</p>
                  <p className="ps-panel__empty-sub">Automated checks passed. Some accessibility issues may require manual testing.</p>
                </div>
              ) : filtered.length === 0 ? (
                <p className="ps-panel__empty" style={{ color: '#6b7280' }}>No {filter} issues.</p>
              ) : (
                filtered.map((iss) => (
                  <div
                    key={iss.id}
                    className="ssi-issue"
                    style={{
                      borderLeftColor: iss.severity === 'critical' ? '#ef4444' : iss.severity === 'warning' ? '#f59e0b' : '#3b82f6',
                      background:      iss.severity === 'critical' ? '#fef2f2' : iss.severity === 'warning' ? '#fffbeb' : '#eff6ff',
                    }}
                  >
                    <div className="ssi-issue__row">
                      <span className={`ps-issue__dot ps-issue__dot--${iss.severity}`} aria-hidden="true" />
                      <div className="ssi-issue__main">
                        <strong className="ssi-issue__title">{iss.title}</strong>
                        <span className="ssi-issue__meta">
                          {iss.severity.charAt(0).toUpperCase() + iss.severity.slice(1)}
                          {iss.wcag  && <> &middot; WCAG {iss.wcag}</>}
                          {iss.count > 1 && <> &middot; {iss.count} elements</>}
                        </span>
                      </div>
                      <button
                        className="aai-btn aai-btn--sm aai-btn--ghost ps-issue__details-btn"
                        onClick={() => setDetailIssue(iss)}
                      >
                        Details
                      </button>
                    </div>
                  </div>
                ))
              )}
            </div>
          </div>

          {/* ── Detail view ── */}
          <div className={`ssi-detail-view${showDetail ? ' ssi-detail-view--in' : ''}`}>
            {detailIssue && (
              <div className="ssi-detail-body">
                {/* Back */}
                <button className="ssi-back" onClick={() => setDetailIssue(null)}>
                  <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 16 16" fill="none" stroke="currentColor" strokeWidth="2" width="13" height="13" aria-hidden="true"><path d="M10 3L5 8l5 5"/></svg>
                  Back to issues
                </button>

                {/* Badge row */}
                <div className="ssi-detail-badge-row">
                  <span className={`idm-badge idm-badge--${detailIssue.severity}`}>{detailIssue.severity}</span>
                  {detailIssue.wcag && <span className="idm-wcag">WCAG {detailIssue.wcag}</span>}
                </div>

                {/* Title + description */}
                <h3 className="ssi-detail-title" style={{ borderTop: `3px solid ${sevColor}`, paddingTop: 10 }}>
                  {detailIssue.title}
                </h3>
                <p className="ssi-detail-desc">{detailIssue.description}</p>

                {/* All affected elements — accordion */}
                {(() => {
                  const allNodes = detailIssue.nodes && detailIssue.nodes.length > 0
                    ? detailIssue.nodes
                    : detailIssue.element ? [{ element: detailIssue.element, selector: detailIssue.selector ?? '' }] : [];
                  if (allNodes.length === 0) return null;
                  const dotColor = sevColor;
                  return (
                    <div className="idm-section">
                      <p className="idm-section-label">
                        Affected element{allNodes.length > 1 ? 's' : ''} ({allNodes.length})
                      </p>
                      <div className="idm-node-list">
                        {allNodes.map((n, i) => {
                          const isOpen = openNodeIdx === i;
                          const label  = n.selector || n.element.slice(0, 60);
                          return (
                            <div
                              key={i}
                              className={`idm-node-item${isOpen ? ' idm-node-item--open' : ''}`}
                              style={{ '--idm-node-color': dotColor } as React.CSSProperties}
                            >
                              <div className="idm-node-hd" onClick={() => setOpenNodeIdx(isOpen ? -1 : i)}>
                                <span className="idm-node-dot" />
                                <span className="idm-node-sel">{label}</span>
                                <span className="idm-node-chevron">›</span>
                              </div>
                              {isOpen && (
                                <div className="idm-node-body">
                                  {n.element && (
                                    <pre style={{ margin: 0, padding: '10px 12px', background: '#f3f4f6', fontSize: 11, fontFamily: 'ui-monospace,SFMono-Regular,monospace', whiteSpace: 'pre-wrap', wordBreak: 'break-word', color: '#374151', lineHeight: 1.5 }}>
                                      <code>{n.element}</code>
                                    </pre>
                                  )}
                                </div>
                              )}
                            </div>
                          );
                        })}
                      </div>
                    </div>
                  );
                })()}

                {/* WCAG link */}
                {detailIssue.help_url && (
                  <a href={detailIssue.help_url} target="_blank" rel="noopener noreferrer" className="idm-learn">
                    {detailIssue.wcag ? `WCAG ${detailIssue.wcag} — ` : ''}View guidance ↗
                  </a>
                )}

                {/* AI actions */}
                <div className="idm-actions">
                  <button
                    className="aai-btn aai-btn--secondary"
                    onClick={() => callAI('fix')}
                    disabled={!hasProvider || run.isPending}
                    title={!hasProvider ? 'Configure an AI provider in Settings' : undefined}
                  >
                    {activeAction === 'fix'
                      ? <><span className="aai-spinner" aria-hidden="true" /> Thinking…</>
                      : 'Generate fix with AI'}
                  </button>
                  <button
                    className="aai-btn aai-btn--ghost"
                    onClick={() => callAI('explain')}
                    disabled={!hasProvider || run.isPending}
                    title={!hasProvider ? 'Configure an AI provider in Settings' : undefined}
                  >
                    {activeAction === 'explain'
                      ? <><span className="aai-spinner aai-spinner--dark" aria-hidden="true" /> Working…</>
                      : 'Explain'}
                  </button>
                </div>

                {!hasProvider && (
                  <p className="aai-muted idm-ai-hint">
                    <a href="#/settings">Configure an AI provider in Settings</a> to enable fix suggestions.
                  </p>
                )}

                {aiError && <p className="aai-error" style={{ marginTop: 12 }}>{aiError}</p>}
                {aiOutput !== null && !aiError && (
                  <div className="idm-ai-output">
                    <p className="idm-ai-label">Suggested fix</p>
                    <p className="idm-ai-disclaimer">AI suggestions are based on automated analysis. Please review before applying.</p>
                    <div className="idm-ai-md" dangerouslySetInnerHTML={{ __html: markdownToHtml(aiOutput) }} />
                  </div>
                )}
              </div>
            )}
          </div>

        </div>{/* end ssi-views */}
      </div>
    </>
  );
}
