"use client";

import { useState } from "react";
import InfiniteVirtualGrid from "@/components/infinite-virtual-grid";
import { FileText } from "lucide-react";

interface TextFile {
  id: number;
  title: string;
  path: string;
  size: number;
  thumbnail: string;
  type: string;
  bookmark_count: number;
  avg_rating: number;
  star_count: number;
}

const TextsPage = () => {
  const [selectedText, setSelectedText] = useState<TextFile | null>(null);
  const [isViewerOpen, setIsViewerOpen] = useState(false);
  const [textContent, setTextContent] = useState<string>("");

  const handleTextClick = async (text: TextFile) => {
    try {
      const response = await fetch(`/api/texts/${text.id}`);
      const data = await response.json();
      setTextContent(data.content);
      setSelectedText(text);
      setIsViewerOpen(true);
    } catch (error) {
      console.error('Error loading text file:', error);
    }
  };

  const handleCloseViewer = () => {
    setIsViewerOpen(false);
    setSelectedText(null);
    setTextContent("");
  };

  const handleBookmark = async (textId: number) => {
    try {
      await fetch(`/api/bookmarks/${textId}`, { method: 'POST' });
    } catch (error) {
      console.error('Error bookmarking text:', error);
    }
  };

  const handleUnbookmark = async (textId: number) => {
    try {
      await fetch(`/api/bookmarks/${textId}`, { method: 'DELETE' });
    } catch (error) {
      console.error('Error unbookmarking text:', error);
    }
  };

  const handleRate = async (textId: number, rating: number) => {
    try {
      await fetch(`/api/stars/${textId}`, {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ rating })
      });
    } catch (error) {
      console.error('Error rating text:', error);
    }
  };

  return (
    <>
      <InfiniteVirtualGrid
        type="text"
        onItemClick={handleTextClick}
        onBookmark={handleBookmark}
        onUnbookmark={handleUnbookmark}
        onRate={handleRate}
      />

      {/* Text Viewer Modal */}
      {isViewerOpen && selectedText && (
        <div className="fixed inset-0 bg-black/90 z-50 flex items-center justify-center p-4">
          <div className="relative w-full max-w-6xl max-h-[90vh] bg-zinc-900 rounded-xl border border-zinc-800">
            {/* Header */}
            <div className="flex items-center justify-between p-4 border-b border-zinc-800">
              <div>
                <h2 className="text-lg font-semibold text-white">{selectedText.title}</h2>
                <p className="text-sm text-zinc-400">{selectedText.path}</p>
              </div>
              <button
                onClick={handleCloseViewer}
                className="p-2 text-zinc-400 hover:text-white hover:bg-zinc-800 rounded-lg transition-colors"
              >
                ✕
              </button>
            </div>

            {/* Content */}
            <div className="p-6 max-h-[calc(90vh-120px)] overflow-auto">
              <pre className="text-sm text-zinc-300 font-mono whitespace-pre-wrap break-words leading-relaxed">
                {textContent}
              </pre>
            </div>

            {/* Footer */}
            <div className="flex items-center justify-between p-4 border-t border-zinc-800">
              <div className="text-sm text-zinc-400">
                Size: {(selectedText.size / 1024).toFixed(2)} KB
              </div>
              <div className="flex gap-2">
                <button
                  onClick={() => navigator.clipboard.writeText(textContent)}
                  className="px-3 py-1 text-sm bg-zinc-800 hover:bg-zinc-700 text-white rounded transition-colors"
                >
                  Copy
                </button>
                <button
                  onClick={() => {
                    const blob = new Blob([textContent], { type: 'text/plain' });
                    const url = URL.createObjectURL(blob);
                    const a = document.createElement('a');
                    a.href = url;
                    a.download = selectedText.title;
                    a.click();
                    URL.revokeObjectURL(url);
                  }}
                  className="px-3 py-1 text-sm bg-blue-600 hover:bg-blue-700 text-white rounded transition-colors"
                >
                  Download
                </button>
              </div>
            </div>
          </div>
        </div>
      )}
    </>
  );
};

export default TextsPage;