'use client';

import { useEffect, useState } from 'react';
import Link from 'next/link';
import { FileText, Download, Table2, FileDown, Clock, Search } from 'lucide-react';
import { cn } from '@/lib/cn';

interface DocumentMeta {
  id: string;
  slug: string;
  title: string;
  description: string;
  type: 'table' | 'report' | 'mixed';
  createdAt: string;
}

const typeLabels: Record<string, { label: string; color: string; bg: string }> = {
  table: { label: 'Таблица', color: 'text-blue-700', bg: 'bg-blue-50' },
  report: { label: 'Отчёт', color: 'text-purple-700', bg: 'bg-purple-50' },
  mixed: { label: 'Смешанный', color: 'text-teal-700', bg: 'bg-teal-50' },
};

export default function DocumentsPage() {
  const [docs, setDocs] = useState<DocumentMeta[]>([]);
  const [loading, setLoading] = useState(true);
  const [search, setSearch] = useState('');

  useEffect(() => {
    fetch('/api/documents')
      .then((res) => res.json() as Promise<{ data: DocumentMeta[] }>)
      .then((res) => setDocs(res.data))
      .catch(() => setDocs([]))
      .finally(() => setLoading(false));
  }, []);

  const filtered = search
    ? docs.filter(
        (d) =>
          d.title.toLowerCase().includes(search.toLowerCase()) ||
          d.description.toLowerCase().includes(search.toLowerCase()),
      )
    : docs;

  if (loading) {
    return (
      <div className="flex items-center justify-center h-64">
        <div className="animate-spin rounded-full h-8 w-8 border-b-2 border-primary" />
      </div>
    );
  }

  return (
    <div>
      <div className="flex items-center justify-between mb-6">
        <div className="flex items-center gap-3">
          <div className="bg-orange-50 p-2.5 rounded-lg">
            <FileText className="h-6 w-6 text-primary" />
          </div>
          <div>
            <h1 className="text-2xl font-bold text-gray-900">Документы</h1>
            <p className="text-sm text-muted">
              Сгенерированные отчёты и документы
            </p>
          </div>
        </div>
      </div>

      {docs.length > 0 && (
        <div className="mb-6">
          <div className="relative">
            <Search className="absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted" />
            <input
              type="text"
              placeholder="Поиск документов..."
              value={search}
              onChange={(e) => setSearch(e.target.value)}
              className="w-full pl-10 pr-4 py-2.5 border border-border rounded-xl text-sm focus:outline-none focus:ring-2 focus:ring-primary/30 focus:border-primary"
            />
          </div>
        </div>
      )}

      {filtered.length === 0 ? (
        <div className="bg-card rounded-xl p-12 shadow-sm border border-border text-center">
          <FileText className="h-12 w-12 text-muted mx-auto mb-4" />
          <h2 className="text-lg font-semibold text-gray-900 mb-2">
            {docs.length === 0 ? 'Нет документов' : 'Ничего не найдено'}
          </h2>
          <p className="text-sm text-muted max-w-md mx-auto">
            {docs.length === 0
              ? 'Документы создаются автоматически при выполнении задач через Telegram. Попросите ассистента сформировать отчёт или аналитику.'
              : 'Попробуйте другой поисковый запрос.'}
          </p>
        </div>
      ) : (
        <div className="space-y-3">
          {filtered.map((doc) => {
            const typeInfo = typeLabels[doc.type] ?? typeLabels['report']!;
            return (
              <Link
                key={doc.id}
                href={`/document/${doc.slug}`}
                className="block bg-card rounded-xl p-5 shadow-sm border border-border hover:border-primary/30 hover:shadow-md transition-all"
              >
                <div className="flex items-start justify-between gap-4">
                  <div className="flex items-start gap-4">
                    <div className="bg-gray-50 p-2.5 rounded-lg shrink-0">
                      {doc.type === 'table' ? (
                        <Table2 className="h-5 w-5 text-blue-600" />
                      ) : (
                        <FileDown className="h-5 w-5 text-purple-600" />
                      )}
                    </div>
                    <div>
                      <h3 className="text-sm font-semibold text-gray-900">
                        {doc.title}
                      </h3>
                      <p className="text-xs text-muted mt-1">
                        {doc.description}
                      </p>
                      <div className="flex items-center gap-3 mt-2">
                        <span
                          className={cn(
                            'text-[10px] font-semibold px-2 py-0.5 rounded-full',
                            typeInfo.bg,
                            typeInfo.color,
                          )}
                        >
                          {typeInfo.label}
                        </span>
                        <span className="flex items-center gap-1 text-[11px] text-muted">
                          <Clock className="h-3 w-3" />
                          {new Date(doc.createdAt).toLocaleDateString('ru-RU', {
                            day: 'numeric',
                            month: 'long',
                            year: 'numeric',
                          })}
                        </span>
                      </div>
                    </div>
                  </div>
                  <Download className="h-4 w-4 text-muted shrink-0 mt-1" />
                </div>
              </Link>
            );
          })}
        </div>
      )}
    </div>
  );
}
