"use client";

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

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

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

export const NotesView: React.FC<NotesViewProps> = ({ onNoteSelect, currentFolder = 'Notes', onNewNote }) => {
  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);
      } catch (err) {
        console.error('Error fetching notes:', err);
        setNotes([]);
      } finally {
        setLoading(false);
      }
    };

    fetchNotes();
  }, [currentFolder]);

  const formatDate = (dateString: string) => {
    return format(new Date(dateString), 'EEEE d MMM yyyy', { 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 formatNoteTitle = (note: Note) => {
    if (currentFolder === 'Diary' || currentFolder === 'Health') {
      // Try to extract date from title (format: YYYY-MM-DD)
      const dateMatch = note.title.match(/^(\d{4}-\d{2}-\d{2})/);
      if (dateMatch) {
        const date = parse(dateMatch[1], 'yyyy-MM-dd', new Date());
        return note.title.replace(dateMatch[1], '').trim();
      }
    }
    return note.title;
  };

  const sortNotes = (notes: Note[]) => {
    return [...notes].sort((a, b) => {
      if (currentFolder === 'Diary' || currentFolder === 'Health') {
        // For Diary and Health, sort by date in title first
        const dateA = a.title.match(/^(\d{4}-\d{2}-\d{2})/);
        const dateB = b.title.match(/^(\d{4}-\d{2}-\d{2})/);
        
        if (dateA && dateB) {
          return new Date(dateB[1]).getTime() - new Date(dateA[1]).getTime();
        }
      }
      // For all folders, sort by lastModified date
      return new Date(b.lastModified).getTime() - new Date(a.lastModified).getTime();
    });
  };

  const Icon = getFolderIcon(currentFolder);

  return (
    <div className="flex flex-col h-full bg-carnet-bg border-r border-carnet-border">
      {/* Header with New Note Button */}
      <div className="p-4 border-b border-carnet-border">
        <div className="flex items-center justify-between mb-4">
          <h2 className="text-lg font-semibold text-carnet-text-primary">{currentFolder}</h2>
          <button
            onClick={onNewNote}
            className="p-2 text-carnet-text-primary hover:bg-carnet-hover rounded-md"
          >
            <Plus className="h-5 w-5" />
          </button>
        </div>
        <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>

      {/* Notes List */}
      <div className="flex-1 overflow-y-auto">
        {loading ? (
          <div className="p-4 text-center text-carnet-text-muted">Chargement...</div>
        ) : notes.length === 0 ? (
          <div className="p-4 text-center text-carnet-text-muted">Aucune note</div>
        ) : (
          <ul className="divide-y divide-carnet-border">
            {sortNotes(notes).map((note) => (
              <li
                key={note.id}
                onClick={() => onNoteSelect?.(note)}
                className="p-4 hover:bg-carnet-hover cursor-pointer"
              >
                <div className="flex items-center space-x-2">
                  <Icon className="h-4 w-4 text-carnet-text-muted" />
                  <div className="flex-1">
                    {currentFolder === 'Diary' || currentFolder === 'Health' ? (
                      <>
                        <div className="text-sm font-medium text-carnet-text-primary">
                          {formatDate(note.lastModified)}
                        </div>
                        <div className="text-sm text-carnet-text-muted">
                          {formatNoteTitle(note)}
                        </div>
                      </>
                    ) : (
                      <>
                        <div className="text-sm font-medium text-carnet-text-primary">
                          {note.title}
                        </div>
                        <div className="text-xs text-carnet-text-muted">
                          {formatDate(note.lastModified)}
                        </div>
                      </>
                    )}
                  </div>
                </div>
              </li>
            ))}
          </ul>
        )}
      </div>
    </div>
  );
}; 