"use client";

import { useEffect, useState, useRef } from "react";
import { useSession } from "next-auth/react";
import { redirect } from "next/navigation";
import Navigation from "@/components/carnet/navigation";
import { NotesView } from "@/components/carnet/notes-view";
import { Editor } from "@/components/carnet/editor";
import { PanelResizer } from "@/components/carnet/panel-resizer";
import { useMediaQuery } from "@/hooks/use-media-query";

// Layout modes
export enum PaneLayout {
  TagSelection = "tag-selection",
  ItemSelection = "item-selection",
  TableView = "table-view",
  Editing = "editing"
}

interface Note {
  id: string;
  title: string;
  content: string;
  lastModified: string;
  type: string;
  mime: string;
  etag: string;
}

export default function CarnetPage() {
  const { data: session, status } = useSession();
  const [isLoading, setIsLoading] = useState(true);
  const [layoutMode, setLayoutMode] = useState<string>("item-selection");
  const [selectedNote, setSelectedNote] = useState<Note | null>(null);
  const [isMobile, setIsMobile] = useState(false);
  const [showNav, setShowNav] = useState(true);
  const [showNotes, setShowNotes] = useState(true);
  const [nextcloudFolders, setNextcloudFolders] = useState<string[]>([]);
  const [selectedFolder, setSelectedFolder] = useState<string>('Notes');
  const [notes, setNotes] = useState<Note[]>([]);
  
  // Panel widths state
  const [navWidth, setNavWidth] = useState(220);
  const [notesWidth, setNotesWidth] = useState(400);
  const [isDraggingNav, setIsDraggingNav] = useState(false);
  const [isDraggingNotes, setIsDraggingNotes] = useState(false);

  // Check screen size
  const isSmallScreen = useMediaQuery("(max-width: 768px)");
  const isMediumScreen = useMediaQuery("(max-width: 1024px)");

  // Cache for Nextcloud folders
  const foldersCache = useRef<{ folders: string[]; timestamp: number } | null>(null);

  useEffect(() => {
    const fetchNextcloudFolders = async () => {
      // Check cache first
      if (foldersCache.current) {
        const cacheAge = Date.now() - foldersCache.current.timestamp;
        if (cacheAge < 5 * 60 * 1000) { // 5 minutes cache
          setNextcloudFolders(foldersCache.current.folders);
          return;
        }
      }

      try {
        const response = await fetch('/api/nextcloud/status');
        if (!response.ok) {
          throw new Error('Failed to fetch Nextcloud folders');
        }
        const data = await response.json();
        const folders = data.folders || [];
        
        // Update cache
        foldersCache.current = {
          folders,
          timestamp: Date.now()
        };
        
        setNextcloudFolders(folders);
      } catch (err) {
        console.error('Error fetching Nextcloud folders:', err);
        setNextcloudFolders([]);
      }
    };

    if (status === "authenticated") {
      fetchNextcloudFolders();
    }
  }, [status]);

  useEffect(() => {
    if (status === "unauthenticated") {
      redirect("/signin");
    }
    if (status !== "loading") {
      setIsLoading(false);
    }
  }, [status]);

  useEffect(() => {
    if (isSmallScreen) {
      setIsMobile(true);
      setShowNav(false);
      setShowNotes(false);
    } else if (isMediumScreen) {
      setIsMobile(false);
      setShowNav(true);
      setShowNotes(false);
    } else {
      setIsMobile(false);
      setShowNav(true);
      setShowNotes(true);
    }
  }, [isSmallScreen, isMediumScreen]);

  // Handle panel resizing
  const handleNavResize = (e: MouseEvent) => {
    if (!isDraggingNav) return;
    const newWidth = e.clientX;
    if (newWidth >= 48 && newWidth <= 400) {
      setNavWidth(newWidth);
    }
  };

  const handleNotesResize = (e: MouseEvent) => {
    if (!isDraggingNotes) return;
    const newWidth = e.clientX - navWidth - 2; // 2px for the resizer
    if (newWidth >= 200) {
      setNotesWidth(newWidth);
    }
  };

  const handleNoteSelect = (note: Note) => {
    setSelectedNote(note);
    if (isMobile) {
      setShowNotes(false);
    }
  };

  const handleNoteSave = async (note: Note) => {
    try {
      const response = await fetch('/api/nextcloud/files', {
        method: note.id ? 'PUT' : 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify({
          id: note.id,
          title: note.title,
          content: note.content,
          folder: selectedFolder
        }),
      });

      if (!response.ok) {
        throw new Error('Failed to save note');
      }

      const savedNote = await response.json();
      setSelectedNote(savedNote);
      
      // Refresh the notes list
      const notesResponse = await fetch(`/api/nextcloud/files?folder=${selectedFolder}`);
      if (notesResponse.ok) {
        const notes = await notesResponse.json();
        setNotes(notes);
      }
    } catch (error) {
      console.error('Error saving note:', error);
    }
  };

  const handleFolderSelect = (folder: string) => {
    console.log('Selected folder:', folder);
    setSelectedFolder(folder);
    setLayoutMode("item-selection");
  };

  const handleNewNote = () => {
    setSelectedNote({
      id: '',
      title: '',
      content: '',
      lastModified: new Date().toISOString(),
      type: 'file',
      mime: 'text/markdown',
      etag: ''
    });
    if (isMobile) {
      setShowNotes(false);
    }
  };

  if (isLoading) {
    return (
      <div className="flex h-screen items-center justify-center">
        <div className="h-32 w-32 animate-spin rounded-full border-t-2 border-b-2 border-gray-900"></div>
      </div>
    );
  }

  return (
    <main className="w-full h-screen bg-black">
      <div className="w-full h-full px-4 pt-12 pb-4">
        <div className="flex h-full bg-carnet-bg">
          {/* Navigation Panel */}
          {showNav && (
            <>
              <div 
                className="flex flex-col h-full bg-carnet-sidebar"
                style={{ width: `${navWidth}px` }}
              >
                <Navigation 
                  nextcloudFolders={nextcloudFolders}
                  onFolderSelect={handleFolderSelect}
                />
              </div>

              {/* Navigation Resizer */}
              <PanelResizer
                isDragging={isDraggingNav}
                onDragStart={() => setIsDraggingNav(true)}
                onDragEnd={() => setIsDraggingNav(false)}
                onDrag={handleNavResize}
              />
            </>
          )}

          {/* Notes Panel */}
          {showNotes && (
            <>
              <div className="flex-1 overflow-hidden">
                <NotesView 
                  onNoteSelect={handleNoteSelect} 
                  currentFolder={selectedFolder}
                  onNewNote={handleNewNote}
                />
              </div>

              {/* Notes Resizer */}
              <PanelResizer
                isDragging={isDraggingNotes}
                onDragStart={() => setIsDraggingNotes(true)}
                onDragEnd={() => setIsDraggingNotes(false)}
                onDrag={handleNotesResize}
              />
            </>
          )}

          {/* Editor Panel */}
          <div className="flex-1 overflow-hidden">
            <Editor 
              note={selectedNote} 
              onSave={handleNoteSave}
              currentFolder={selectedFolder}
            />
          </div>

          {/* Mobile Navigation Toggle */}
          {isMobile && (
            <div className="fixed bottom-4 right-4 flex space-x-2">
              <button
                className="p-2 rounded-full bg-primary text-white"
                onClick={() => setShowNav(!showNav)}
              >
                {showNav ? 'Hide Nav' : 'Show Nav'}
              </button>
              <button
                className="p-2 rounded-full bg-primary text-white"
                onClick={() => setShowNotes(!showNotes)}
              >
                {showNotes ? 'Hide Notes' : 'Show Notes'}
              </button>
            </div>
          )}
        </div>
      </div>
    </main>
  );
}