'use client';

import { getDocument, Document } from '@/lib/api';
import { useEffect, useState } from 'react';
import { useParams } from 'next/navigation';
import { FileText, Tag, ArrowLeft, Loader2, Calendar } from 'lucide-react';
import Link from 'next/link';

export default function DocumentPage() {
  const { id } = useParams<{ id: string }>();
  const [doc, setDoc] = useState<Document | null>(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState('');

  useEffect(() => {
    getDocument(id)
      .then(setDoc)
      .catch(() => setError('Document not found'))
      .finally(() => setLoading(false));
  }, [id]);

  if (loading) return (
    <div className="flex justify-center items-center h-40">
      <Loader2 className="animate-spin text-brain-500" size={32} />
    </div>
  );

  if (error || !doc) return (
    <div className="text-red-600 p-4">{error || 'Document not found'}</div>
  );

  return (
    <div className="max-w-3xl mx-auto">
      <Link href="/search" className="inline-flex items-center gap-1 text-sm text-slate-500 hover:text-brain-600 mb-4">
        <ArrowLeft size={14} /> Back to Search
      </Link>

      <div className="bg-white rounded-xl border border-slate-200 p-8">
        <div className="flex items-start gap-3 mb-4">
          <FileText className="text-brain-500 mt-1 shrink-0" size={24} />
          <div>
            <h1 className="text-2xl font-bold text-slate-900">{doc.title}</h1>
            <p className="text-sm text-slate-400 mt-1">{doc.path}</p>
          </div>
        </div>

        <div className="flex flex-wrap gap-4 text-sm text-slate-500 mb-6 pb-6 border-b border-slate-100">
          {doc.word_count && (
            <span>{doc.word_count.toLocaleString()} words</span>
          )}
          {doc.indexed_at && (
            <span className="flex items-center gap-1">
              <Calendar size={13} />
              Indexed {new Date(doc.indexed_at).toLocaleDateString()}
            </span>
          )}
        </div>

        {doc.tags.length > 0 && (
          <div className="flex flex-wrap gap-2 mb-6">
            {doc.tags.map((tag) => (
              <Link
                key={tag}
                href={`/tags?tag=${encodeURIComponent(tag)}`}
                className="text-xs bg-brain-50 text-brain-700 px-2.5 py-1 rounded-full flex items-center gap-1 hover:bg-brain-100"
              >
                <Tag size={10} />
                {tag}
              </Link>
            ))}
          </div>
        )}

        {doc.frontmatter && typeof doc.frontmatter === 'object' && 'summary' in doc.frontmatter && (
          <div className="mb-6 p-4 bg-slate-50 rounded-lg border border-slate-100">
            <p className="text-sm font-medium text-slate-600 mb-1">Summary</p>
            <p className="text-sm text-slate-700">{String((doc.frontmatter as Record<string, unknown>).summary)}</p>
          </div>
        )}

        <div className="prose max-w-none text-slate-700 whitespace-pre-wrap font-mono text-sm leading-relaxed bg-slate-50 rounded-lg p-5 overflow-x-auto">
          {doc.content}
        </div>
      </div>
    </div>
  );
}
