"use client";

import React, { useState, useEffect } from 'react';
import { Save } from 'lucide-react';
import dynamic from 'next/dynamic';

// Dynamically import the editor to avoid SSR issues
const ReactQuill = dynamic(() => import('react-quill'), { ssr: false });
import 'react-quill/dist/quill.snow.css';

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

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

export function Editor({ note, onSave, currentFolder }: EditorProps) {
  const [content, setContent] = useState('');
  const [isSaving, setIsSaving] = useState(false);
  const [isLoading, setIsLoading] = useState(false);

  useEffect(() => {
    if (note?.content) {
      setIsLoading(true);
      setContent(note.content);
      setIsLoading(false);
    } else {
      setContent('');
    }
  }, [note]);

  const handleSave = async () => {
    if (!note) return;
    
    setIsSaving(true);
    try {
      const updatedNote = {
        ...note,
        content,
        lastModified: new Date().toISOString(),
        size: content.length
      };
      onSave(updatedNote);
    } catch (error) {
      console.error('Failed to save note:', error);
    } finally {
      setIsSaving(false);
    }
  };

  if (isLoading) {
    return (
      <div className="p-4">
        <div className="h-4 w-full bg-gray-200 rounded animate-pulse"></div>
      </div>
    );
  }

  if (!note) {
    return (
      <div className="flex items-center justify-center h-full">
        <p className="text-gray-500">Select a note to edit</p>
      </div>
    );
  }

  return (
    <div className="flex flex-col h-full">
      <div className="flex items-center justify-between p-4 border-b">
        <h2 className="text-xl font-semibold">{note.title}</h2>
        <button
          onClick={handleSave}
          disabled={isSaving}
          className="flex items-center space-x-2 px-4 py-2 bg-primary text-white rounded-lg hover:bg-primary/90 disabled:opacity-50"
        >
          <Save className="h-4 w-4" />
          <span>{isSaving ? 'Saving...' : 'Save'}</span>
        </button>
      </div>
      
      <div className="flex-1 overflow-y-auto p-4">
        <ReactQuill
          theme="snow"
          value={content}
          onChange={setContent}
          className="h-full"
          modules={{
            toolbar: [
              [{ header: [1, 2, 3, false] }],
              ['bold', 'italic', 'underline', 'strike'],
              [{ list: 'ordered' }, { list: 'bullet' }],
              ['link', 'image'],
              ['clean']
            ]
          }}
        />
      </div>
    </div>
  );
} 