"use client";

import React, { useState, useEffect } from 'react';
import { Search, Plus, X, FileText, Calendar, Heart, Users } from 'lucide-react';
import { format } from 'date-fns';
import { fr } from 'date-fns/locale';

interface Note {
  id: string;
  title: string;
  content: string;
  lastEdited: Date;
  category?: string;
  tags?: string[];
}

interface NotesViewProps {
  onNoteSelect?: (note: Note) => void;
  currentFolder?: string;
}

export const NotesView: React.FC<NotesViewProps> = ({ onNoteSelect, currentFolder = 'Notes' }) => {
  const [searchQuery, setSearchQuery] = useState('');
  const [notes, setNotes] = useState<Note[]>([]);
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    const fetchNotes = async () => {
      try {
        setLoading(true);
        const response = await fetch(`/api/nextcloud/files?folder=${currentFolder}`);
        if (!response.ok) {
          throw new Error('Failed to fetch notes');
        }
        const data = await response.json();
        setNotes(data.files || []);
      } catch (err) {
        console.error('Error fetching notes:', err);
        setNotes([]);
      } finally {
        setLoading(false);
      }
    };

    fetchNotes();
  }, [currentFolder]);

  const handleNewNote = () => {
    const newNote: Note = {
      id: Date.now().toString(),
      title: 'New Note',
      content: '',
      lastEdited: new Date()
    };
    setNotes([newNote, ...notes]);
    onNoteSelect?.(newNote);
  };

  const formatDate = (date: Date) => {
    return format(date, 'EEEE d MMM yyyy, HH:mm', { locale: fr });
  };

  const getFolderIcon = (folder: string) => {
    switch (folder) {
      case 'Notes':
        return FileText;
      case 'Diary':
        return Calendar;
      case 'Health':
        return Heart;
      case 'Contacts':
        return Users;
      default:
        return FileText;
    }
  };

  const Icon = getFolderIcon(currentFolder);

  return (
    <div className="flex flex-col h-full bg-carnet-bg border-r border-carnet-border">
      {/* Search Header */}
      <div className="p-4 border-b border-carnet-border">
        <div className="relative">
          <input
            type="text"
            value={searchQuery}
            onChange={(e) => setSearchQuery(e.target.value)}
            placeholder="Rechercher des notes..."
            className="w-full pl-9 pr-4 py-2 bg-white border border-carnet-border rounded-md text-sm text-carnet-text-primary placeholder-carnet-text-muted focus:outline-none focus:ring-1 focus:ring-primary"
          />
          <Search className="absolute left-3 top-2.5 h-4 w-4 text-carnet-text-muted" />
          {searchQuery && (
            <button
              onClick={() => setSearchQuery('')}
              className="absolute right-3 top-2.5 text-carnet-text-muted hover:text-carnet-text-primary"
            >
              <X className="h-4 w-4" />
            </button>
          )}
        </div>
      </div>

      {/* Folder Header */}
      <div className="px-4 py-3 border-b border-carnet-border flex items-center justify-between">
        <div className="flex items-center">
          <Icon className="w-4 h-4 mr-2 text-carnet-text-muted" />
          <span className="text-sm font-medium text-carnet-text-primary">{currentFolder}</span>
        </div>
        <button 
          className="p-1.5 rounded-md hover:bg-carnet-hover"
          onClick={handleNewNote}
        >
          <Plus className="w-4 h-4 text-carnet-text-muted" />
        </button>
      </div>

      {/* Notes List */}
      <div className="flex-1 overflow-y-auto">
        {loading ? (
          <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>
        ) : notes.length === 0 ? (
          <div className="flex items-center justify-center h-full">
            <p className="text-sm text-carnet-text-muted">Aucune note trouvée</p>
          </div>
        ) : (
          notes.map((note) => (
            <div 
              key={note.id}
              className="px-4 py-3 border-b border-carnet-border hover:bg-carnet-hover cursor-pointer"
              onClick={() => onNoteSelect?.(note)}
            >
              <div className="flex flex-col">
                <div className="flex items-center">
                  <span className="text-sm font-medium text-carnet-text-primary">
                    {note.title}
                  </span>
                  {note.tags?.map((tag) => (
                    <span 
                      key={tag}
                      className="ml-2 px-1.5 py-0.5 bg-carnet-tag-finance-bg rounded text-xs font-medium text-carnet-tag-finance-text"
                    >
                      {tag}
                    </span>
                  ))}
                </div>
                <div className="mt-1 flex items-center text-xs text-carnet-text-muted">
                  <span>{formatDate(note.lastEdited)}</span>
                  {note.content && (
                    <>
                      <span className="mx-1.5">•</span>
                      <span>{note.content}</span>
                    </>
                  )}
                </div>
              </div>
            </div>
          ))
        )}
      </div>
    </div>
  );
}; 