import { useState } from 'react';
import type { Card, Column, DocPage, ReferenceType } from '../../lib/kanbanApi';
import type { CustomPage } from '../../lib/pagesApi';
import { ReferenceLinks } from './ReferenceLinks';
import { AgentRunBar } from './AgentRunBar';
import type { UseOrchestrator } from './useOrchestrator';

/**
 * Full-detail overlay for a single kanban card.
 *
 * Opened by clicking a card on the board. Surfaces everything: the agent
 * orchestrator (run/steer/stop/diff/merge/bevy), column moves, reference
 * management, tags, and comments. Opening the modal also opens the run's live
 * SSE stream (via the embedded AgentRunBar) so activity streams in real time.
 */

const COLUMN_LABELS: Record<Column, string> = {
  done: 'Done',
  'in-progress': 'In Progress',
  todo: 'Todo',
  backlog: 'Backlog',
};

interface CardModalProps {
  card: Card;
  pages: DocPage[];
  customPages: CustomPage[];
  orch: UseOrchestrator;
  onClose: () => void;
  onMove: (status: Column) => void;
  onAddComment: (text: string) => void;
  onDeleteComment: (commentId: string) => void;
  onAddTag: (tag: string) => void;
  onRemoveTag: (tag: string) => void;
  onAddReference: (ref: { label: string; type: ReferenceType; href: string }) => void;
  onRemoveReference: (href: string) => void;
}

export function CardModal(props: CardModalProps) {
  const { card, pages, customPages, orch, onClose } = props;
  const [commentDraft, setCommentDraft] = useState('');
  const [tagDraft, setTagDraft] = useState('');
  const [refDraft, setRefDraft] = useState('');
  const [customRefDraft, setCustomRefDraft] = useState('');

  const availablePages = pages.filter((p) => !card.references.some((r) => r.href === p.path));
  const availableCustomPages = customPages.filter(
    (p) => !card.references.some((r) => r.href === `/docs/custom/${p.slug}`),
  );

  return (
    <div style={overlayStyle} onClick={onClose}>
      <div
        className="max-h-[90vh] w-full max-w-3xl overflow-y-auto rounded-2xl border border-border bg-surface p-6 shadow-2xl"
        onClick={(e) => e.stopPropagation()}
      >
        {/* Header */}
        <div className="mb-5 flex items-start gap-3">
          <span style={badgeStyle}>{card.id}</span>
          <span style={categoryStyle}>{card.category}</span>
          <div className="ml-auto flex items-center gap-2">
            <label className="font-mono text-[0.7rem] uppercase tracking-wider text-muted">Move to</label>
            <select
              value={card.status}
              onChange={(e) => props.onMove(e.target.value as Column)}
              style={inputStyle}
            >
              {(Object.keys(COLUMN_LABELS) as Column[]).map((c) => (
                <option key={c} value={c}>
                  {COLUMN_LABELS[c]}
                </option>
              ))}
            </select>
            <button
              className="cursor-pointer rounded border border-border bg-transparent px-2 py-0.5 text-muted hover:text-fg"
              onClick={onClose}
            >
              ✕
            </button>
          </div>
        </div>

        <h2 className="m-0 mb-2 text-xl text-fg-bright">{card.title}</h2>
        <p className="m-0 mb-1 text-[0.9rem] leading-relaxed text-fg-dim">{card.description}</p>
        <p className="m-0 mb-4 text-[0.82rem] italic leading-relaxed text-fg-dim">{card.details}</p>

        {(card.files || card.notes) && (
          <div className="mb-4 flex flex-col gap-1">
            {card.files && (
              <div className="font-mono text-[0.7rem] text-muted">📁 {card.files}</div>
            )}
            {card.notes && <div style={noteStyle}>💡 {card.notes}</div>}
          </div>
        )}

        {/* Agent orchestrator */}
        <Section title="Agent">
          <AgentRunBar card={card} orch={orch} />
        </Section>

        {/* References */}
        <Section title={`References (${card.references.length})`}>
          {availablePages.length > 0 && (
            <div className="mb-3">
              <label className="mb-1 block text-[0.75rem] text-fg-dim">Add doc reference:</label>
              <div className="flex items-center gap-2">
                <select value={refDraft} onChange={(e) => setRefDraft(e.target.value)} style={inputStyle}>
                  <option value="">Select a doc page…</option>
                  {availablePages.map((p) => (
                    <option key={p.path} value={p.path}>
                      {p.icon} {p.title}
                    </option>
                  ))}
                </select>
                {refDraft && (
                  <button
                    type="button"
                    style={smallButtonStyle}
                    onClick={() => {
                      const page = pages.find((p) => p.path === refDraft);
                      if (page) {
                        props.onAddReference({ label: page.title, type: 'doc', href: page.path });
                        setRefDraft('');
                      }
                    }}
                  >
                    Add
                  </button>
                )}
              </div>
            </div>
          )}
          {availableCustomPages.length > 0 && (
            <div className="mb-3">
              <label className="mb-1 block text-[0.75rem] text-purple">Add custom page reference:</label>
              <div className="flex items-center gap-2">
                <select
                  value={customRefDraft}
                  onChange={(e) => setCustomRefDraft(e.target.value)}
                  style={inputStyle}
                >
                  <option value="">Select a custom page…</option>
                  {availableCustomPages.map((p) => (
                    <option key={p.id} value={p.slug}>
                      {p.icon} {p.title}
                    </option>
                  ))}
                </select>
                {customRefDraft && (
                  <button
                    type="button"
                    style={smallButtonStyle}
                    onClick={() => {
                      const page = customPages.find((p) => p.slug === customRefDraft);
                      if (page) {
                        props.onAddReference({
                          label: page.title,
                          type: 'custom',
                          href: `/docs/custom/${page.slug}`,
                        });
                        setCustomRefDraft('');
                      }
                    }}
                  >
                    Add
                  </button>
                )}
              </div>
            </div>
          )}
          <ReferenceLinks
            references={card.references}
            pages={pages}
            customPages={customPages}
            onRemove={(href) => props.onRemoveReference(href)}
          />
        </Section>

        {/* Tags */}
        <Section title={`Tags (${card.tags.length})`}>
          <div className="mb-2 flex items-center gap-2">
            <input
              type="text"
              placeholder="Add tag…"
              value={tagDraft}
              onChange={(e) => setTagDraft(e.target.value)}
              onKeyDown={(e) => {
                if (e.key === 'Enter' && tagDraft.trim()) {
                  props.onAddTag(tagDraft.trim());
                  setTagDraft('');
                }
              }}
              style={{ ...inputStyle, flex: 1 }}
            />
            <button
              type="button"
              style={smallButtonStyle}
              onClick={() => {
                if (tagDraft.trim()) {
                  props.onAddTag(tagDraft.trim());
                  setTagDraft('');
                }
              }}
            >
              Tag
            </button>
          </div>
          {card.tags.length > 0 ? (
            <div className="flex flex-wrap gap-1">
              {card.tags.map((tag) => (
                <span key={tag} style={tagStyle} onClick={() => props.onRemoveTag(tag)} title="Click to remove tag">
                  🏷️ {tag} ×
                </span>
              ))}
            </div>
          ) : (
            <p className="m-0 text-[0.8rem] italic text-muted">No tags yet</p>
          )}
        </Section>

        {/* Comments */}
        <Section title={`Comments (${card.comments.length})`}>
          <div className="mb-2 flex items-center gap-2">
            <input
              type="text"
              placeholder="Add a comment…"
              value={commentDraft}
              onChange={(e) => setCommentDraft(e.target.value)}
              onKeyDown={(e) => {
                if (e.key === 'Enter' && commentDraft.trim()) {
                  props.onAddComment(commentDraft.trim());
                  setCommentDraft('');
                }
              }}
              style={{ ...inputStyle, flex: 1 }}
            />
            <button
              type="button"
              style={primaryButtonStyle}
              onClick={() => {
                if (commentDraft.trim()) {
                  props.onAddComment(commentDraft.trim());
                  setCommentDraft('');
                }
              }}
            >
              Post
            </button>
          </div>
          {card.comments.length > 0 ? (
            <div className="max-h-[260px] overflow-y-auto">
              {card.comments.map((comment) => (
                <div key={comment.id} style={commentStyle}>
                  <div className="mb-1 flex items-center justify-between">
                    <span className="font-medium text-fg">{comment.author}</span>
                    <button
                      type="button"
                      onClick={() => props.onDeleteComment(comment.id)}
                      title="Delete comment"
                      style={deleteBtnStyle}
                    >
                      ✕
                    </button>
                  </div>
                  <div className="text-[0.8rem] leading-relaxed text-fg-dim">{comment.text}</div>
                  <div className="mt-1 font-mono text-[0.65rem] text-muted">
                    {new Date(comment.createdAt).toLocaleString()}
                  </div>
                </div>
              ))}
            </div>
          ) : (
            <p className="m-0 text-[0.8rem] italic text-muted">No comments yet</p>
          )}
        </Section>
      </div>
    </div>
  );
}

// --- subcomponents & styles ------------------------------------------------

function Section({ title, children }: { title: string; children: React.ReactNode }) {
  return (
    <div className="mb-5 border-t border-border pt-4">
      <h3 className="m-0 mb-3 text-[0.78rem] font-semibold uppercase tracking-wider text-fg-dim">{title}</h3>
      {children}
    </div>
  );
}

const overlayStyle: React.CSSProperties = {
  position: 'fixed',
  inset: 0,
  background: 'rgba(0,0,0,0.6)',
  backdropFilter: 'blur(2px)',
  display: 'flex',
  alignItems: 'center',
  justifyContent: 'center',
  zIndex: 50,
  padding: 'var(--sp-4)',
};

const badgeStyle: React.CSSProperties = {
  fontFamily: 'var(--font-mono)',
  fontSize: '0.7rem',
  color: 'var(--muted)',
  background: 'var(--surface-raised)',
  padding: '2px 8px',
  borderRadius: 'var(--radius-sm)',
};

const categoryStyle: React.CSSProperties = {
  fontSize: '0.72rem',
  color: 'var(--fg-dim)',
  background: 'rgba(100,100,100,0.1)',
  padding: '2px 8px',
  borderRadius: 'var(--radius-sm)',
};

const noteStyle: React.CSSProperties = {
  fontSize: '0.72rem',
  color: 'var(--accent)',
  padding: '4px 8px',
  background: 'rgba(240,160,48,0.08)',
  borderRadius: 'var(--radius-sm)',
  borderLeft: '2px solid var(--accent)',
};

const tagStyle: React.CSSProperties = {
  fontSize: '0.68rem',
  padding: '2px 8px',
  background: 'rgba(100,150,255,0.1)',
  border: '1px solid rgba(100,150,255,0.3)',
  borderRadius: 'var(--radius-sm)',
  cursor: 'pointer',
};

const inputStyle: React.CSSProperties = {
  padding: '4px 8px',
  fontSize: '0.82rem',
  background: 'var(--surface)',
  border: '1px solid var(--border)',
  borderRadius: 'var(--radius-sm)',
  color: 'var(--fg)',
};

const smallButtonStyle: React.CSSProperties = {
  padding: '4px 12px',
  fontSize: '0.8rem',
  background: 'var(--surface)',
  border: '1px solid var(--border)',
  borderRadius: 'var(--radius-sm)',
  cursor: 'pointer',
  color: 'var(--fg)',
};

const primaryButtonStyle: React.CSSProperties = {
  padding: '6px 16px',
  fontSize: '0.8rem',
  background: 'var(--accent)',
  border: 'none',
  borderRadius: 'var(--radius-sm)',
  cursor: 'pointer',
  color: 'var(--surface)',
};

const commentStyle: React.CSSProperties = {
  padding: '8px 10px',
  marginBottom: '8px',
  background: 'var(--surface-raised)',
  borderRadius: 'var(--radius-sm)',
};

const deleteBtnStyle: React.CSSProperties = {
  border: 'none',
  background: 'transparent',
  color: 'var(--muted)',
  cursor: 'pointer',
  fontSize: '0.7rem',
  padding: 0,
  lineHeight: 1,
};
