interface Document {
  id: number | null;
  title: string;
  content: string;
  author?: string;
  created_at?: string;
  updated_at?: string;
}

interface DocsTableProps {
  docs: Document[];
  onEdit: (doc: Document) => void;
  onNew: () => void;
  onDelete: (id: number) => Promise<void>;
}

const formatDate = (dateString?: string) => {
  if (!dateString) return "Never";
  const date = new Date(dateString);
  const now = new Date();
  const diff = now.getTime() - date.getTime();
  const hours = Math.floor(diff / (1000 * 60 * 60));
  const days = Math.floor(diff / (1000 * 60 * 60 * 24));
  
  if (hours < 1) return "Just now";
  if (hours < 24) return `${hours}h ago`;
  if (days < 7) return `${days}d ago`;
  
  return date.toLocaleDateString("en-US", { month: "short", day: "numeric" });
};

const getPreviewText = (content: string, lines: number = 3) => {
  const contentLines = content.split("\n").filter(l => l.trim());
  return contentLines
    .slice(0, lines)
    .map(line => line.replace(/^[=\-\*#]+\s+/, "").trim())
    .filter(l => l)
    .join(" ")
    .substring(0, 200);
};

export default function DocsTable({ docs, onEdit, onNew, onDelete }: DocsTableProps) {
  return (
    <section>
      <div className="table-header">
        <h2>Documents</h2>
        <button onClick={onNew} style={{ width: "auto" }}>
          + New Document
        </button>
      </div>
      
      {docs.length === 0 ? (
        <div className="empty-state">
          <p>No documents yet</p>
          <p className="hint">Create your first document to get started</p>
        </div>
      ) : (
        <div className="docs-grid">
          {docs.map((doc, idx) => (
            <div key={doc.id ?? idx} className="doc-card">
              <div className="card-header">
                <h3>{doc.title || `Untitled ${idx + 1}`}</h3>
                <span className="char-count">
                  {doc.content.length} chars
                </span>
              </div>
              
              <div className="card-preview">
                {getPreviewText(doc.content) || <em>No content yet</em>}
              </div>
              
              <div className="card-meta">
                {doc.author && <span className="author">By {doc.author}</span>}
                <span className="date">{formatDate(doc.updated_at)}</span>
              </div>
              
              <div className="card-actions">
                <button 
                  className="small-btn" 
                  onClick={() => onEdit(doc)}
                >
                  Edit
                </button>
                {doc.id !== null && (
                  <button 
                    className="small-btn btn-danger" 
                    onClick={() => onDelete(doc.id as number)}
                  >
                    Delete
                  </button>
                )}
              </div>
            </div>
          ))}
        </div>
      )}
    </section>
  );
}
