import { useEffect, useState } from 'react';
import { api } from '../lib/api.ts';
import ReactMarkdown from 'react-markdown';
import remarkGfm from 'remark-gfm';

interface DocSummary {
  id: string;
  channel_id: string;
  creator_id: string;
  title: string;
  created_at: string;
  updated_at: string;
}

interface DocDetail extends DocSummary {
  content: string;
}

interface DocsViewProps {
  channelId: string;
  channelName: string;
}

export function DocsView({ channelId, channelName }: DocsViewProps) {
  const [docs, setDocs] = useState<DocSummary[]>([]);
  const [activeDoc, setActiveDoc] = useState<DocDetail | null>(null);
  const [editing, setEditing] = useState(false);
  const [title, setTitle] = useState('');
  const [content, setContent] = useState('');
  const [loading, setLoading] = useState(false);
  const [showNew, setShowNew] = useState(false);
  const [newTitle, setNewTitle] = useState('');

  useEffect(() => {
    setLoading(true);
    api.get<DocSummary[]>(`/channels/${channelId}/docs`)
      .then((data) => setDocs(Array.isArray(data) ? data : []))
      .finally(() => setLoading(false));
  }, [channelId]);

  const openDoc = async (id: string) => {
    const d = await api.get<DocDetail>(`/channels/docs/${id}`);
    setActiveDoc(d);
    setTitle(d.title);
    setContent(d.content);
    setEditing(false);
  };

  const createDoc = async () => {
    if (!newTitle.trim()) return;
    const d = await api.post<DocDetail>(`/channels/${channelId}/docs`, { title: newTitle, content: '' });
    setDocs((prev) => [{ id: d.id, channel_id: d.channel_id, creator_id: d.creator_id, title: d.title, created_at: d.created_at, updated_at: d.updated_at }, ...prev]);
    setShowNew(false);
    setNewTitle('');
    openDoc(d.id);
  };

  const saveDoc = async () => {
    if (!activeDoc) return;
    const d = await api.patch<DocDetail>(`/channels/docs/${activeDoc.id}`, { title, content });
    setActiveDoc(d);
    setDocs((prev) => prev.map((s) => s.id === d.id ? { ...s, title: d.title, updated_at: d.updated_at } : s));
    setEditing(false);
  };

  const deleteDoc = async (id: string) => {
    if (!confirm('Delete this doc?')) return;
    await api.delete(`/channels/docs/${id}`);
    setDocs((prev) => prev.filter((d) => d.id !== id));
    if (activeDoc?.id === id) setActiveDoc(null);
  };

  return (
    <div className="flex flex-col h-full bg-gb-bg">
      <div className="terminal-border border-t-0 border-x-0 px-3 py-2 text-gb-fg-s flex items-center justify-between">
        <span>☰ {channelName}</span>
        <button onClick={() => setShowNew((p) => !p)} className="text-xs text-gb-fg-f hover:text-gb-orange font-mono">[NEW DOC]</button>
      </div>
      {showNew && (
        <div className="p-3 border-b border-gb-bg-t font-mono text-xs flex items-center gap-2">
          <input value={newTitle} onChange={(e) => setNewTitle(e.target.value)} placeholder="doc title" className="terminal-input flex-1" />
          <button onClick={createDoc} disabled={!newTitle.trim()} className="px-2 py-1 bg-gb-orange text-gb-bg disabled:opacity-50">[CREATE]</button>
        </div>
      )}
      <div className="flex flex-1 min-h-0">
        <div className="w-48 shrink-0 overflow-y-auto border-r border-gb-bg-t font-mono text-xs">
          {loading && <div className="p-2 text-gb-fg-f">[loading...]</div>}
          {!loading && docs.length === 0 && <div className="p-2 text-gb-fg-s">[no docs]</div>}
          {docs.map((d) => (
            <div
              key={d.id}
              onClick={() => openDoc(d.id)}
              className={`p-2 cursor-pointer truncate ${activeDoc?.id === d.id ? 'bg-gb-bg-t text-gb-fg' : 'text-gb-fg-s hover:bg-gb-bg-s'}`}
            >
              {d.title}
              <div className="text-[10px] text-gb-fg-f">updated {new Date(d.updated_at).toLocaleDateString()}</div>
            </div>
          ))}
        </div>
        <div className="flex-1 flex flex-col min-w-0">
          {!activeDoc && (
            <div className="flex-1 flex items-center justify-center text-gb-fg-s font-mono text-xs">
              select or create a doc
            </div>
          )}
          {activeDoc && !editing && (
            <div className="flex-1 overflow-y-auto p-3">
              <div className="flex items-center justify-between mb-2">
                <h2 className="text-gb-fg font-bold text-sm">{activeDoc.title}</h2>
                <div className="flex gap-2 text-xs font-mono">
                  <button onClick={() => setEditing(true)} className="text-gb-fg-f hover:text-gb-orange">[EDIT]</button>
                  <button onClick={() => deleteDoc(activeDoc.id)} className="text-gb-red hover:text-gb-orange">[DEL]</button>
                </div>
              </div>
              <div className="text-gb-fg text-sm prose prose-invert max-w-none">
                <ReactMarkdown remarkPlugins={[remarkGfm]}>{activeDoc.content || '*empty*'}</ReactMarkdown>
              </div>
            </div>
          )}
          {activeDoc && editing && (
            <div className="flex-1 flex flex-col p-3 gap-2">
              <input value={title} onChange={(e) => setTitle(e.target.value)} className="terminal-input w-full text-sm font-bold" />
              <textarea value={content} onChange={(e) => setContent(e.target.value)} className="terminal-input flex-1 font-mono text-xs resize-none" />
              <div className="flex gap-2 text-xs font-mono">
                <button onClick={saveDoc} className="px-2 py-1 bg-gb-orange text-gb-bg">[SAVE]</button>
                <button onClick={() => setEditing(false)} className="text-gb-fg-f hover:text-gb-orange">[CANCEL]</button>
              </div>
            </div>
          )}
        </div>
      </div>
    </div>
  );
}
