'use client';

import { useEffect, useRef, useState } from 'react';
import { useParams, useRouter } from 'next/navigation';
import { ArrowLeft, FileDown, Printer, Table2, FileText } from 'lucide-react';
import { api, ApiError } from '@/lib/api';

interface DocumentData {
  id: string;
  slug: string;
  title: string;
  description: string;
  type: 'table' | 'report' | 'mixed';
  content: string; // HTML content
  createdAt: string;
}

export default function DocumentDetailPage() {
  const params = useParams();
  const router = useRouter();
  const id = params.id as string;

  const contentRef = useRef<HTMLDivElement>(null);
  const [doc, setDoc] = useState<DocumentData | null>(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);

  useEffect(() => {
    api
      .get<DocumentData>(`/admin/documents/${id}`)
      .then((data) => setDoc(data))
      .catch((err) => {
        if (err instanceof ApiError && err.status === 404) {
          setError('Документ не найден');
        } else {
          setError(err instanceof Error ? err.message : 'Ошибка загрузки');
        }
      })
      .finally(() => setLoading(false));
  }, [id]);

  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>
    );
  }

  if (error || !doc) {
    return (
      <div className="flex flex-col items-center justify-center h-64 gap-4">
        <FileText className="h-12 w-12 text-muted" />
        <p className="text-sm text-error">{error || 'Документ не найден'}</p>
        <button
          onClick={() => router.push('/documents')}
          className="text-sm text-primary hover:underline"
        >
          Вернуться к списку
        </button>
      </div>
    );
  }

  const handleExport = async (format: 'docx' | 'xlsx') => {
    try {
      const response = await fetch(
        `${process.env.NEXT_PUBLIC_API_URL || 'http://localhost:3000/v1'}/admin/documents/${id}/export?format=${format}`,
        {
          headers: {
            Authorization: `Bearer ${localStorage.getItem('accessToken') || ''}`,
          },
        },
      );
      if (!response.ok) throw new Error('Export failed');
      const blob = await response.blob();
      const url = URL.createObjectURL(blob);
      const a = document.createElement('a');
      a.href = url;
      a.download = `${doc.slug}.${format}`;
      a.click();
      URL.revokeObjectURL(url);
    } catch {
      alert('Экспорт пока недоступен');
    }
  };

  const handleDownloadPdf = async () => {
    const el = contentRef.current;
    if (!el) return;
    const html2canvas = (await import('html2canvas-pro')).default;
    const { jsPDF } = await import('jspdf');
    const canvas = await html2canvas(el, { scale: 2, useCORS: true });
    const imgData = canvas.toDataURL('image/png');
    const pdf = new jsPDF('p', 'mm', 'a4');
    const pdfW = pdf.internal.pageSize.getWidth();
    const pdfH = pdf.internal.pageSize.getHeight();
    const imgW = pdfW - 16;
    const imgH = (canvas.height * imgW) / canvas.width;
    let y = 8;
    let page = 0;
    while (y < imgH + 8) {
      if (page > 0) pdf.addPage();
      pdf.addImage(imgData, 'PNG', 8, 8 - y + 8 * (page === 0 ? 0 : 1), imgW, imgH);
      y += pdfH - 16;
      page++;
    }
    pdf.save(`${doc.slug}.pdf`);
  };

  return (
    <div>
      <button
        onClick={() => router.push('/documents')}
        className="flex items-center gap-2 text-sm text-muted hover:text-gray-900 mb-6 transition-colors"
      >
        <ArrowLeft className="h-4 w-4" />
        Все документы
      </button>

      <div ref={contentRef} className="bg-card rounded-xl shadow-sm border border-border overflow-hidden">
        {/* Header */}
        <div className="px-6 py-5 border-b border-border flex items-center justify-between">
          <div>
            <h1 className="text-xl font-bold text-gray-900">{doc.title}</h1>
            <p className="text-sm text-muted mt-1">{doc.description}</p>
            <p className="text-xs text-muted mt-2">
              {new Date(doc.createdAt).toLocaleDateString('ru-RU', {
                day: 'numeric',
                month: 'long',
                year: 'numeric',
                hour: '2-digit',
                minute: '2-digit',
              })}
            </p>
          </div>
          <div className="flex gap-2 print:hidden">
            <button
              onClick={() => void handleDownloadPdf()}
              className="flex items-center gap-2 border border-border bg-card text-gray-700 px-4 py-2 rounded-xl text-sm font-medium hover:bg-background transition-colors"
            >
              <FileDown className="h-4 w-4" />
              PDF
            </button>
            {(doc.type === 'report' || doc.type === 'mixed') && (
              <button
                onClick={() => void handleExport('docx')}
                className="flex items-center gap-2 border border-border bg-card text-gray-700 px-4 py-2 rounded-xl text-sm font-medium hover:bg-background transition-colors"
              >
                <FileDown className="h-4 w-4" />
                DOCX
              </button>
            )}
            {(doc.type === 'table' || doc.type === 'mixed') && (
              <button
                onClick={() => void handleExport('xlsx')}
                className="flex items-center gap-2 border border-border bg-card text-gray-700 px-4 py-2 rounded-xl text-sm font-medium hover:bg-background transition-colors"
              >
                <Table2 className="h-4 w-4" />
                XLSX
              </button>
            )}
            <button
              onClick={() => window.print()}
              className="flex items-center gap-2 border border-border bg-card text-gray-700 px-4 py-2 rounded-xl text-sm font-medium hover:bg-background transition-colors"
            >
              <Printer className="h-4 w-4" />
              Печать
            </button>
          </div>
        </div>

        {/* Content */}
        <div
          className="px-6 py-6 prose prose-sm max-w-none
            prose-headings:text-gray-900 prose-p:text-gray-700
            prose-table:border-collapse prose-th:bg-gray-50 prose-th:px-4 prose-th:py-2 prose-th:text-left prose-th:text-sm prose-th:font-medium prose-th:text-muted prose-th:border prose-th:border-border
            prose-td:px-4 prose-td:py-2 prose-td:text-sm prose-td:border prose-td:border-border"
          dangerouslySetInnerHTML={{ __html: doc.content }}
        />
      </div>
    </div>
  );
}
