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

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

const WCAG_URL: Record<string, string> = {
  '1.1.1': 'https://www.w3.org/WAI/WCAG21/Understanding/non-text-content.html',
  '1.4.3': 'https://www.w3.org/WAI/WCAG21/Understanding/contrast-minimum.html',
  '2.1.1': 'https://www.w3.org/WAI/WCAG21/Understanding/keyboard.html',
  '2.4.7': 'https://www.w3.org/WAI/WCAG21/Understanding/focus-visible.html',
  '3.1.1': 'https://www.w3.org/WAI/WCAG21/Understanding/language-of-page.html',
  '4.1.2': 'https://www.w3.org/WAI/WCAG21/Understanding/name-role-value.html',
};

/** Renders an AI suggestion with full markdown formatting. */
function AiSuggestion({ text }: { text: string }) {
  return (
    <div className="detail-panel__ai-output">
      <p className="detail-panel__code-label">Suggested fix</p>
      <div className="detail-panel__ai-md" dangerouslySetInnerHTML={{ __html: markdownToHtml(text) }} />
    </div>
  );
}

export default function DetailPanel({ 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);

  if (!issue) {
    return (
      <div className="detail-panel detail-panel--empty">
        <p>Select an issue to see details.</p>
      </div>
    );
  }

  const wcagUrl = WCAG_URL[issue.wcag];

  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 (
    <aside className="detail-panel" aria-label="Issue detail">
      <div className="detail-panel__header">
        <span className={`issue-row__badge issue-row__badge--${issue.severity}`}>
          {issue.severity}
        </span>
        <button
          className="detail-panel__close"
          onClick={() => { onClose(); setAiOutput(null); setAiError(null); }}
          aria-label="Close detail panel"
        >
          ✕
        </button>
      </div>

      <h3 className="detail-panel__title">{issue.title}</h3>

      <dl className="detail-panel__meta">
        <dt>WCAG</dt>
        <dd>
          {wcagUrl ? (
            <a href={wcagUrl} target="_blank" rel="noreferrer noopener">
              {issue.wcag}
            </a>
          ) : (
            issue.wcag
          )}
        </dd>
        <dt>Selector</dt>
        <dd><code>{issue.selector || '—'}</code></dd>
        <dt>Instances</dt>
        <dd>{issue.count}</dd>
      </dl>

      <p className="detail-panel__description">{issue.description}</p>

      {issue.element && (
        <div className="detail-panel__code-block">
          <p className="detail-panel__code-label">Example element</p>
          <pre><code>{issue.element}</code></pre>
        </div>
      )}

      {/* AI actions */}
      <div className="detail-panel__actions">
        {issue.ai_fixable && (
          <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…</> : 'Suggest Fix'}
          </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 detail-panel__ai-hint">
          Configure an AI provider in <a href="#/settings">Settings</a> to unlock AI features.
        </p>
      )}

      {/* AI output */}
      {aiError && <p className="aai-error">{aiError}</p>}
      {aiOutput !== null && !aiError && (
        <AiSuggestion text={aiOutput} />
      )}
    </aside>
  );
}
