import { useLayoutEffect, useState, useRef, useEffect } from "react";
import { pdfjs, Document, Page } from "react-pdf";
import { ArrowBackIcon, ArrowForwardIcon, MenuBookIcon, MyLocationIcon } from "./icons/Icons";

import structureOriginal from "./structure.json";

const structure = structureOriginal.map((topic) => ({ ...topic, version: 0 }));

pdfjs.GlobalWorkerOptions.workerSrc = `//unpkg.com/pdfjs-dist@${pdfjs.version}/build/pdf.worker.min.mjs`;

export function TopicListView({ selectedIndex, onChange }) {
  const itemRefs = useRef([]);

  useLayoutEffect(() => {
    if (selectedIndex !== null) {
      itemRefs.current?.[Math.max(selectedIndex - 3, 0)].scrollIntoView();
    }
  }, [selectedIndex]);

  return (
    <>
      <div className="flex-1 relative overflow-y-scroll">
        {structure.map((topic, i) => (
          <div
            key={topic.id}
            ref={(node) => {
              itemRefs.current[i] = node;
            }}
            onClick={() => onChange(i)}
            className={`flex px-2 py-1 rounded-md cursor-pointer border-l-4 ${selectedIndex === i ? "bg-blue-100 border-blue-500" : "border-transparent hover:bg-gray-100"}`}
          >
            <div
              className={`w-6 flex-shrink-0 flex font-medium justify-end ${selectedIndex === i ? "text-blue-600" : "text-blue-800"}`}
            >
              {i + 1}
            </div>
            <span className="ml-2">
              <span className={`leading-5 ${selectedIndex === i ? "font-medium" : "font-normal"}`}>
                {topic.title}
              </span>
            </span>
          </div>
        ))}
        {selectedIndex !== null && (
          <div className="sticky bottom-0 p-2 w-full flex flex-col">
            <div className="w-full flex justify-between items-center gap-2">
              <button
                className="w-full p-2 bg-blue-600 hover:bg-blue-700 cursor-pointer truncate rounded-md text-sm text-white text-center shadow-md transition-colors"
                onClick={() => onChange(selectedIndex)}
              >
                <span>Продължи четенето:</span>
                <br />
                <span className="font-medium">{structure[selectedIndex].title}</span>
              </button>
              <button
                className="px-3 py-3 bg-teal-500 hover:bg-teal-300 cursor-pointer rounded-full flex items-center justify-center shadow-md transition-colors"
                onClick={() => {
                  itemRefs.current?.[Math.max(selectedIndex - 3, 0)].scrollIntoView({
                    behavior: "smooth",
                  });
                }}
              >
                <MyLocationIcon className="h-5 w-5" />
              </button>
            </div>
          </div>
        )}
      </div>
    </>
  );
}

function Layout({ children, title }) {
  return (
    <div className="max-w-xl mx-auto h-full relative flex flex-col">
      <div className="w-full p-4 font-medium text-large text-white bg-blue-600">
        <span className="line-clamp-2">{title}</span>
      </div>
      {children}
    </div>
  );
}

export default function App() {
  const [isMenuOpen, setIsMenuOpen] = useState(true);
  const [selectedIndex, setSelectedIndex] = useState(null);
  const [versions, setVersions] = useState(Array.from({ length: structure.length }, () => 0));

  function handleChange(i) {
    setSelectedIndex(i);
    setIsMenuOpen(false);
  }

  if (isMenuOpen) {
    return (
      <Layout title="Конспект за Държавен Изпит">
        <TopicListView selectedIndex={selectedIndex} onChange={handleChange} />
      </Layout>
    );
  }

  return (
    <Layout title={`${selectedIndex + 1}: ${structure[selectedIndex].title}`}>
      <div className="flex-1 overflow-y-scroll">
        <Reader
          key={structure[selectedIndex].files[versions[selectedIndex]]}
          file={structure[selectedIndex].files[versions[selectedIndex]]}
        />
        <div className="absolute bottom-14 flex justify-between p-2 w-full z-999">
          <button
            className="cursor-pointer p-2 rounded-full bg-blue-600 text-white"
            onClick={() => {
              setIsMenuOpen(true);
            }}
          >
            <MenuBookIcon className="fill-gray-100" />
          </button>
          <div className="flex space-x-1">
            {structure[selectedIndex].files.map((file, vIndex) => (
              <button
                key={file}
                className={`flex-1 cursor-pointer px-2 py-1 rounded-md text-xs whitespace-nowrap ${
                  versions[selectedIndex] === vIndex
                    ? "bg-blue-100 text-blue-800 font-medium"
                    : "bg-gray-100 hover:bg-gray-200"
                }`}
                onClick={() => {
                  setVersions((prev) => {
                    const newVersions = [...prev];
                    newVersions[selectedIndex] = vIndex;
                    return newVersions;
                  });
                }}
              >
                Version {vIndex + 1}
              </button>
            ))}
          </div>
        </div>
      </div>
      <div className="w-full flex flex-col space-y-2">
        <div className="flex bg-gray-100 border-t border-blue-200 text-center">
          {selectedIndex === 0 ? (
            <div className="flex-1 border-r border-blue-200" />
          ) : (
            <div
              onClick={() => setSelectedIndex((prev) => prev - 1)}
              className="border-r border-blue-200 w-1/2 flex-1 p-4 hover:bg-blue-200 cursor-pointer flex align-center justify-start"
            >
              <ArrowBackIcon />
              <span className="ml-2 truncate w-full ">
                {selectedIndex}: {structure[selectedIndex - 1].title}
              </span>
            </div>
          )}
          {selectedIndex === structure.length - 1 ? (
            <div className="flex-1" />
          ) : (
            <div
              onClick={() => setSelectedIndex((prev) => prev + 1)}
              className="flex-1 p-4 hover:bg-blue-200 w-1/2 cursor-pointer flex align-center justify-end"
            >
              <span className="mr-2 w-full truncate">
                {selectedIndex + 2}: {structure[selectedIndex + 1].title}
              </span>
              <ArrowForwardIcon />
            </div>
          )}
        </div>
      </div>
    </Layout>
  );
}

export function Reader({ file }) {
  const [content, setContent] = useState(null);
  const [isLoading, setIsLoading] = useState(true);
  const [error, setError] = useState(null);

  useEffect(() => {
    const fetchFile = async () => {
      try {
        setIsLoading(true);
        const response = await fetch(`/files_html/${file}`);

        if (!response.ok) {
          throw new Error(`Failed to load file: ${response.status}`);
        }

        let fileContent = await response.text();

        // If no head tag, add a basic HTML structure with fonts
        fileContent = `
            <!DOCTYPE html>
            <html>
            <head>
              <meta charset="UTF-8">
              <meta name="viewport" content="width=device-width, initial-scale=1.0">
              <link rel="stylesheet" href="https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700&display=swap">
              <style>
                body {
                  font-family: 'Inter', -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Helvetica, Arial, sans-serif;
                  line-height: 1.5;
                  color: #333;
                  padding: 20px;
                  -webkit-font-smoothing: antialiased;
                  -moz-osx-font-smoothing: grayscale;
                  padding-bottom: 56px;
                }
                pre, code {
                  font-family: 'SF Mono', Menlo, Monaco, Consolas, 'Liberation Mono', 'Courier New', monospace;
                }
              </style>
            </head>
            <body>
              ${fileContent}
            </body>
            </html>
          `;

        setContent(fileContent);
        setError(null);
      } catch (err) {
        console.error("Error loading file:", err);
        setError(err.message);
      } finally {
        setIsLoading(false);
      }
    };

    fetchFile();
  }, [file]);

  if (error) {
    return <div className="text-red-500 p-4 border border-red-300 rounded">Error: {error}</div>;
  }

  if (isLoading) {
    return (
      <div className="p-4 flex justify-center items-center h-40">
        <div className="animate-pulse">Loading...</div>
      </div>
    );
  }

  return (
    <div className="w-full h-full border border-gray-300 rounded overflow-hidden">
      <iframe
        srcDoc={content}
        title={`File: ${file}`}
        className="w-full h-full border-0"
        key={file}
        allow="fullscreen"
      />
    </div>
  );
}
