"use client";

import { useEffect, useState } 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 Header from "@/components/carnet/header";
import { useMediaQuery } from "@/hooks/use-media-query";
import { toast } from "sonner";

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

interface Note {
  id: string;
  title: string;
  content: string;
  lastEdited: Date;
}

interface NextcloudStatus {
  isConnected: boolean;
  folders: string[];
  error?: string;
}

export default function CarnetPage() {
  const { data: session, status } = useSession();
  const [layout, setLayout] = useState<PaneLayout>(PaneLayout.ItemSelection);
  const [nextcloudFolders, setNextcloudFolders] = useState<string[]>([]);
  const [selectedFolder, setSelectedFolder] = useState<string | null>(null);
  const [isLoading, setIsLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);
  const [selectedNote, setSelectedNote] = useState<Note | null>(null);
  const [isMobile, setIsMobile] = useState(false);
  const [showNav, setShowNav] = useState(true);
  const [showNotes, setShowNotes] = useState(true);
  
  // 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)");

  useEffect(() => {
    const fetchNextcloudFolders = async () => {
      try {
        const response = await fetch('/api/nextcloud/status');
        if (!response.ok) {
          throw new Error('Failed to fetch Nextcloud folders');
        }
        const data = await response.json();
        setNextcloudFolders(data.folders || []);
        setError(null);
      } catch (err) {
        setError(err instanceof Error ? err.message : 'An error occurred');
        setNextcloudFolders([]);
      } finally {
        setIsLoading(false);
      }
    };

    fetchNextcloudFolders();
  }, []);

  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 = (note: Note) => {
    // TODO: Implement note saving logic
    console.log('Saving note:', note);
  };

  const handleFolderSelect = (folder: string) => {
    setSelectedFolder(folder);
    setLayout(PaneLayout.ItemSelection);
  };

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

  if (error) {
    return (
      <div className="flex items-center justify-center h-screen">
        <div className="text-red-500">{error}</div>
      </div>
    );
  }

  return (
    <div className="flex h-screen bg-carnet-background">
      <Navigation 
        layout={layout}
        onLayoutChange={setLayout}
        nextcloudFolders={nextcloudFolders}
        onFolderSelect={handleFolderSelect}
      />
      <div className="flex-1 flex flex-col mt-14">
        <div className="flex-1 overflow-hidden">
          {selectedFolder ? (
            <div className="p-6">
              <h2 className="text-2xl font-semibold mb-4">{selectedFolder}</h2>
              {/* Add your folder content here */}
            </div>
          ) : (
            <div className="flex h-full">
              {showNotes && (
                <>
                  <div style={{ width: notesWidth }}>
                    <NotesView onNoteSelect={handleNoteSelect} />
                  </div>
                  <PanelResizer
                    isDragging={isDraggingNotes}
                    onDragStart={() => setIsDraggingNotes(true)}
                    onDragEnd={() => setIsDraggingNotes(false)}
                    onDrag={handleNotesResize}
                  />
                </>
              )}
              <div className="flex-1">
                <Editor note={selectedNote} onSave={handleNoteSave} />
              </div>
            </div>
          )}
        </div>
      </div>
    </div>
  );
} 