"use client";

import React, { useState, useEffect, useRef } from 'react';
import { Image, FileText, Link, List, Plus } from 'lucide-react';

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

interface EditorProps {
  note?: Note | null;
  onSave?: (note: Note) => void;
  currentFolder?: string;
  onRefresh?: () => void;
}

export const Editor: React.FC<EditorProps> = ({ note, onSave, currentFolder = 'Notes', onRefresh }) => {
  const [title, setTitle] = useState(note?.title || '');
  const [content, setContent] = useState(note?.content || '');
  const [isSaving, setIsSaving] = useState(false);
  const [isLoading, setIsLoading] = useState(false);
  const saveTimeout = useRef<NodeJS.Timeout>();

  useEffect(() => {
    const fetchNoteContent = async () => {
      if (note?.id) {
        setIsLoading(true);
        try {
          const response = await fetch(`/api/nextcloud/files/content?id=${note.id}`);
          if (!response.ok) {
            throw new Error('Failed to fetch note content');
          }
          const data = await response.json();
          setContent(data.content);
        } catch (error) {
          console.error('Error fetching note content:', error);
        } finally {
          setIsLoading(false);
        }
      }
    };

    if (note) {
      setTitle(note.title);
      if (note.id) {
        fetchNoteContent();
      } else {
        setContent('');
      }
    } else {
      setTitle('');
      setContent('');
    }
  }, [note]);

  const handleTitleChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    setTitle(e.target.value);
    debouncedSave();
  };

  const handleContentChange = (e: React.ChangeEvent<HTMLTextAreaElement>) => {
    setContent(e.target.value);
    debouncedSave();
  };

  const debouncedSave = () => {
    if (saveTimeout.current) {
      clearTimeout(saveTimeout.current);
    }
    saveTimeout.current = setTimeout(() => {
      handleSave();
    }, 1000); // Save after 1 second of inactivity
  };

  const handleSave = async () => {
    if (!title || !content) return;
    
    setIsSaving(true);
    try {
      const endpoint = note?.id ? '/api/nextcloud/files' : '/api/nextcloud/files';
      const method = note?.id ? 'PUT' : 'POST';
      
      const response = await fetch(endpoint, {
        method,
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify({
          id: note?.id,
          title,
          content,
          folder: currentFolder
        }),
      });

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

      const savedNote = await response.json();
      onSave?.({
        ...savedNote,
        content
      });
      onRefresh?.();
    } catch (error) {
      console.error('Error saving note:', error);
    } finally {
      setIsSaving(false);
    }
  };

  if (!note) {
    return (
      <div className="flex flex-col h-full bg-carnet-bg items-center justify-center">
        <div className="text-center">
          <FileText className="h-12 w-12 text-carnet-text-muted mx-auto mb-4" />
          <h2 className="text-xl font-semibold text-carnet-text-primary mb-2">
            Sélectionnez une note
          </h2>
          <p className="text-carnet-text-muted">
            Choisissez une note existante ou créez-en une nouvelle
          </p>
        </div>
      </div>
    );
  }

  return (
    <div className="flex flex-col h-full bg-carnet-bg">
      {/* Title Bar */}
      <div className="p-4 border-b border-carnet-border">
        <input
          type="text"
          value={title}
          onChange={handleTitleChange}
          placeholder="Titre"
          className="w-full text-xl font-semibold text-carnet-text-primary placeholder-carnet-text-muted focus:outline-none bg-transparent"
        />
      </div>

      {/* Editor Area */}
      <div className="flex-1 p-4">
        {isLoading ? (
          <div className="flex items-center justify-center h-full">
            <div className="animate-spin rounded-full h-8 w-8 border-t-2 border-b-2 border-primary"></div>
          </div>
        ) : (
          <textarea
            value={content}
            onChange={handleContentChange}
            placeholder="Ecrire..."
            className="w-full h-full resize-none focus:outline-none bg-transparent text-carnet-text-primary placeholder-carnet-text-muted"
          />
        )}
      </div>
      {isSaving && (
        <div className="absolute bottom-4 right-4 text-sm text-carnet-text-muted">
          Enregistrement...
        </div>
      )}
    </div>
  );
}; 