"use client";

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

const FOLDER_DISPLAY_NAMES: Record<string, string> = {
  'Notes': 'Bloc-notes',
  'Diary': 'Journal',
  'Health': 'Carnet de santé',
  'Contacts': 'Carnet d\'adresses'
};

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

interface NotesViewProps {
  notes: Note[];
  onNoteSelect?: (note: Note) => void;
  currentFolder?: string;
  onNewNote?: () => void;
  loading?: boolean;
  onDeleteNote?: (note: Note) => void;
}

export const NotesView: React.FC<NotesViewProps> = ({ 
  notes, 
  onNoteSelect, 
  currentFolder = 'Notes', 
  onNewNote,
  loading = false,
  onDeleteNote,
  onRefresh
}) => {
  const [searchQuery, setSearchQuery] = useState('');
  const [hoveredNote, setHoveredNote] = useState<string | null>(null);
  const [noteToDelete, setNoteToDelete] = useState<Note | null>(null);

  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 (!note.title) {
      return 'Sans titre';
    }
    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();
        }
        // If one has a date and the other doesn't, prioritize the one with date
        if (dateA && !dateB) return -1;
        if (!dateA && dateB) return 1;
      }
      // For all folders, sort by lastModified date
      const timeA = a.lastModified ? new Date(a.lastModified).getTime() : 0;
      const timeB = b.lastModified ? new Date(b.lastModified).getTime() : 0;
      return timeB - timeA;
    });
  };

  const Icon = getFolderIcon(currentFolder);

  return (
    <div className="flex flex-col h-full bg-carnet-bg border-r border-carnet-border">
      {/* Confirmation Dialog */}
      {noteToDelete && (
        <div className="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50">
          <div className="bg-carnet-bg p-6 rounded-lg shadow-lg max-w-md w-full">
            <h3 className="text-lg font-semibold text-carnet-text-primary mb-4">
              Supprimer la note
            </h3>
            <p className="text-carnet-text-muted mb-6">
              Êtes-vous sûr de vouloir supprimer la note "{noteToDelete.title}" ? Cette action est irréversible.
            </p>
            <div className="flex justify-end space-x-4">
              <button
                onClick={() => setNoteToDelete(null)}
                className="px-4 py-2 text-carnet-text-primary hover:bg-carnet-hover rounded-md"
              >
                Annuler
              </button>
              <button
                onClick={() => {
                  onDeleteNote?.(noteToDelete);
                  setNoteToDelete(null);
                }}
                className="px-4 py-2 bg-red-500 text-white hover:bg-red-600 rounded-md"
              >
                Supprimer
              </button>
            </div>
          </div>
        </div>
      )}

      {/* Header with New Note Button */}
      <div className="p-4 border-b border-carnet-border">
        <div className="flex items-center justify-between mb-4">
          <div className="flex items-center space-x-2">
            <Icon className="h-5 w-5 text-carnet-text-primary" />
            <h2 className="text-lg font-semibold text-carnet-text-primary">
              {FOLDER_DISPLAY_NAMES[currentFolder] || currentFolder}
            </h2>
          </div>
          <div className="flex items-center space-x-2">
            {onRefresh && (
              <button
                onClick={onRefresh}
                className="p-2 text-carnet-text-primary hover:bg-carnet-hover rounded-md"
                title="Rafraîchir"
              >
                <RefreshCw className="h-5 w-5" />
              </button>
            )}
            <button
              onClick={onNewNote}
              className="p-2 text-carnet-text-primary hover:bg-carnet-hover rounded-md"
              title="Nouvelle note"
            >
              <Plus className="h-5 w-5" />
            </button>
          </div>
        </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, index) => (
              <li
                key={note.id || `note-${index}`}
                onMouseEnter={() => setHoveredNote(note.id)}
                onMouseLeave={() => setHoveredNote(null)}
                className="p-4 hover:bg-carnet-hover cursor-pointer group"
              >
                <div className="flex items-center justify-between">
                  <div 
                    className="flex items-center space-x-2 flex-1"
                    onClick={() => onNoteSelect?.(note)}
                  >
                    <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 font-medium text-carnet-text-primary">
                            {note.title}
                          </div>
                          <div className="text-xs text-carnet-text-muted">
                            {formatDate(note.lastModified)}
                          </div>
                        </>
                      )}
                    </div>
                  </div>
                  {currentFolder === 'Notes' && hoveredNote === note.id && (
                    <button
                      onClick={(e) => {
                        e.stopPropagation();
                        setNoteToDelete(note);
                      }}
                      className="p-1 text-carnet-text-muted hover:text-red-500 opacity-0 group-hover:opacity-100 transition-opacity"
                    >
                      <X className="h-4 w-4" />
                    </button>
                  )}
                </div>
              </li>
            ))}
          </ul>
        )}
      </div>
    </div>
  );
}; 