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

export interface ModalIssue {
  title:       string;
  severity:    string;
  wcag?:       string;
  selector?:   string;
  element?:    string;
  description: string;
  count?:      number;
  ai_fixable?: boolean;
  help_url?:   string;
}

interface Props {
  issue:   ModalIssue | null;
  onClose: () => void;
}

/** Renders AI response with full markdown formatting. */
function AiSuggestion({ text }: { text: string }) {
  return (
    <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(text) }} />
    </div>
  );
}

export default function IssueDetailModal({ issue, onClose }: Props) {
  const { run, hasProvider } = useAI();
  const [aiOutput, setAiOutput]       = useState<string | null>(null);
  const [aiError, setAiError]         = useState<string | null>(null);
  const [activeAction, setActiveAction] = useState<string | null>(null);

  // Reset AI state when switching issues
  useEffect(() => {
    setAiOutput(null);
    setAiError(null);
  }, [issue?.title, issue?.selector]);

  // Scroll lock + Escape key
  useEffect(() => {
    if (!issue) return;
    const prev = document.body.style.overflow;
    document.body.style.overflow = 'hidden';
    const handler = (e: KeyboardEvent) => { if (e.key === 'Escape') onClose(); };
    document.addEventListener('keydown', handler);
    return () => {
      document.body.style.overflow = prev;
      document.removeEventListener('keydown', handler);
    };
  }, [issue, onClose]);

  if (!issue) return null;

  const sevColor =
    issue.severity === 'critical' ? '#ef4444' :
    issue.severity === 'warning'  ? '#f59e0b' : '#3b82f6';

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

  return (
    <div className="idm-backdrop" onClick={onClose} role="presentation">
      <div
        className="idm"
        role="dialog"
        aria-label="Issue details"
        aria-modal="true"
        onClick={(e) => e.stopPropagation()}
      >
        {/* Top border accent + header */}
        <div className="idm-hd" style={{ borderTop: `3px solid ${sevColor}` }}>
          <div className="idm-hd-left">
            <span className={`idm-badge idm-badge--${issue.severity}`}>{issue.severity}</span>
            {issue.wcag && <span className="idm-wcag">WCAG {issue.wcag}</span>}
          </div>
          <button className="idm-close" onClick={onClose} aria-label="Close">×</button>
        </div>

        {/* Scrollable body */}
        <div className="idm-body">
          <h2 className="idm-title">{issue.title}</h2>
          <p className="idm-desc">{issue.description}</p>
          <p className="idm-review-hint">This issue may affect accessibility for some users and should be reviewed.</p>

          {(issue.selector || issue.count !== undefined) && (
            <dl className="idm-meta">
              {issue.selector && (
                <>
                  <dt>Selector</dt>
                  <dd><code className="idm-code">{issue.selector}</code></dd>
                </>
              )}
              {issue.count !== undefined && (
                <>
                  <dt>Instances</dt>
                  <dd>{issue.count}</dd>
                </>
              )}
            </dl>
          )}

          {issue.element && (
            <div className="idm-section">
              <p className="idm-section-label">Affected element</p>
              <pre className="idm-pre"><code>{issue.element}</code></pre>
            </div>
          )}

          {issue.help_url && (
            <a
              href={issue.help_url}
              target="_blank"
              rel="noopener noreferrer"
              className="idm-learn"
            >
              {issue.wcag ? `WCAG ${issue.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 ? 'Enable AI to generate fix suggestions' : 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 ? 'Enable AI to generate fix suggestions' : 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 && <AiSuggestion text={aiOutput} />}
        </div>
      </div>
    </div>
  );
}
