'use client';

import { useState } from 'react';
import { Note } from '@/services/notes';
import { Search, Plus, Calendar, Trash2, GripVertical } from 'lucide-react';
import { formatDistanceToNow } from 'date-fns';
import { fr } from 'date-fns/locale';
import { Tag } from '@/lib/types';
import {
  DndContext,
  closestCenter,
  KeyboardSensor,
  PointerSensor,
  useSensor,
  useSensors,
  DragEndEvent,
} from '@dnd-kit/core';
import {
  arrayMove,
  SortableContext,
  sortableKeyboardCoordinates,
  useSortable,
  verticalListSortingStrategy,
} from '@dnd-kit/sortable';
import { CSS } from '@dnd-kit/utilities';

interface NotesListProps {
  notes: Note[];
  onSelectNote: (note: Note) => void;
  onCreateNote: () => void;
  onDeleteNote: (noteId: string) => void;
  onReorderNotes: (noteOrders: Array<{ id: string; order: number }>) => void;
  selectedNoteId?: string;
  isLoading?: boolean;
  availableTags?: Tag[];
}

// Extraire le titre du contenu markdown
function getNoteTitle(content: string): string {
  const firstLine = content.split('\n')[0] || '';
  const title = firstLine
    .replace(/^#{1,6}\s+/, '') // Remove markdown headers
    .replace(/\*\*(.*?)\*\*/g, '$1') // Remove bold
    .replace(/\*(.*?)\*/g, '$1') // Remove italic
    .replace(/`(.*?)`/g, '$1') // Remove inline code
    .trim();
  return title || 'Note sans titre';
}

// Composant pour un item de note sortable
function SortableNoteItem({
  note,
  isSelected,
  onSelect,
  onDelete,
  showDeleteConfirm,
  setShowDeleteConfirm,
}: {
  note: Note;
  isSelected: boolean;
  onSelect: () => void;
  onDelete: (noteId: string, e: React.MouseEvent) => void;
  showDeleteConfirm: string | null;
  setShowDeleteConfirm: (id: string | null) => void;
}) {
  const {
    attributes,
    listeners,
    setNodeRef,
    transform,
    transition,
    isDragging,
  } = useSortable({ id: note.id });

  const style = {
    transform: CSS.Transform.toString(transform),
    transition,
    opacity: isDragging ? 0.5 : 1,
  };

  return (
    <div
      ref={setNodeRef}
      style={style}
      className={`group relative p-3 rounded-lg cursor-pointer transition-all ${
        isSelected
          ? 'bg-[var(--primary)]/20 border-l-4 border-[var(--primary)]'
          : 'hover:bg-[var(--card)]/50 border-l-4 border-transparent'
      }`}
      onClick={onSelect}
    >
      <div className="flex items-start gap-2">
        {/* Drag handle */}
        <div
          {...attributes}
          {...listeners}
          className="cursor-grab active:cursor-grabbing mt-1 opacity-0 group-hover:opacity-100 transition-opacity"
        >
          <GripVertical className="w-4 h-4 text-[var(--muted-foreground)]" />
        </div>

        <div className="flex-1 min-w-0">
          <div className="flex items-start justify-between gap-2 mb-1">
            <h3 className="font-medium text-sm text-[var(--foreground)] truncate">
              {getNoteTitle(note.content)}
            </h3>
            {showDeleteConfirm === note.id ? (
              <div className="flex gap-1">
                <button
                  onClick={(e) => {
                    e.stopPropagation();
                    onDelete(note.id, e);
                  }}
                  className="p-1 rounded-md bg-[var(--destructive)] text-white text-xs"
                >
                  Confirmer
                </button>
                <button
                  onClick={(e) => {
                    e.stopPropagation();
                    setShowDeleteConfirm(null);
                  }}
                  className="p-1 rounded-md bg-[var(--muted)] text-[var(--foreground)] text-xs"
                >
                  Annuler
                </button>
              </div>
            ) : (
              <button
                onClick={(e) => {
                  e.stopPropagation();
                  setShowDeleteConfirm(note.id);
                }}
                className="opacity-0 group-hover:opacity-100 p-1 rounded-md hover:bg-[var(--destructive)]/20 text-[var(--destructive)] transition-opacity"
              >
                <Trash2 className="w-3 h-3" />
              </button>
            )}
          </div>
          <div className="flex items-center justify-between gap-2 text-xs text-[var(--muted-foreground)]">
            <div className="flex items-center gap-2">
              <Calendar className="w-3 h-3" />
              <span>
                {formatDistanceToNow(new Date(note.updatedAt), {
                  addSuffix: true,
                  locale: fr,
                })}
              </span>
            </div>
            {note.tags && note.tags.length > 0 && (
              <div className="flex gap-1 flex-shrink-0">
                {note.tags.map((tagName) => (
                  <span
                    key={tagName}
                    className="px-2 py-0.5 rounded-full text-xs bg-[var(--primary)]/10 text-[var(--primary)] whitespace-nowrap"
                  >
                    {tagName}
                  </span>
                ))}
              </div>
            )}
          </div>
        </div>
      </div>
    </div>
  );
}

export function NotesList({
  notes,
  onSelectNote,
  onCreateNote,
  onDeleteNote,
  onReorderNotes,
  selectedNoteId,
  isLoading = false,
}: NotesListProps) {
  const [searchQuery, setSearchQuery] = useState('');
  const [showDeleteConfirm, setShowDeleteConfirm] = useState<string | null>(
    null
  );

  const sensors = useSensors(
    useSensor(PointerSensor),
    useSensor(KeyboardSensor, {
      coordinateGetter: sortableKeyboardCoordinates,
    })
  );

  // Filter notes based on search query
  const filteredNotes = notes.filter(
    (note) =>
      note.title.toLowerCase().includes(searchQuery.toLowerCase()) ||
      note.content.toLowerCase().includes(searchQuery.toLowerCase())
  );

  const handleDragEnd = (event: DragEndEvent) => {
    const { active, over } = event;

    if (!over || active.id === over.id) {
      return;
    }

    const oldIndex = filteredNotes.findIndex((note) => note.id === active.id);
    const newIndex = filteredNotes.findIndex((note) => note.id === over.id);

    const reorderedNotes = arrayMove(filteredNotes, oldIndex, newIndex);

    // Calculer les nouveaux ordres
    const noteOrders = reorderedNotes.map((note, index) => ({
      id: note.id,
      order: index,
    }));

    onReorderNotes(noteOrders);
  };

  const handleDeleteConfirm = (noteId: string) => {
    onDeleteNote(noteId);
    setShowDeleteConfirm(null);
  };

  return (
    <div className="flex flex-col h-full bg-[var(--card)]/40 backdrop-blur-md border-r border-[var(--border)]/60 relative before:absolute before:inset-0 before:bg-gradient-to-br before:from-[color-mix(in_srgb,var(--primary)_8%,transparent)] before:via-[color-mix(in_srgb,var(--primary)_4%,transparent)] before:to-transparent before:opacity-80 before:pointer-events-none">
      {/* Header */}
      <div className="p-4 border-b border-[var(--border)]">
        <div className="space-y-3">
          <button
            onClick={onCreateNote}
            className="w-full flex items-center justify-center gap-2 px-3 py-2 bg-[var(--primary)]/85 hover:bg-[var(--primary)] text-[var(--primary-foreground)] rounded-md text-sm font-medium transition-all duration-200 shadow-lg shadow-[var(--primary)]/20 hover:shadow-xl hover:shadow-[var(--primary)]/30"
          >
            <Plus className="w-4 h-4" />
            Nouvelle note
          </button>

          {/* Search */}
          <div className="relative">
            <Search className="pointer-events-none absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-[var(--muted-foreground)]" />
            <input
              type="text"
              placeholder="Rechercher une note"
              value={searchQuery}
              onChange={(e) => setSearchQuery(e.target.value)}
              className="w-full pl-10 pr-4 py-2 border border-[var(--border)]/60 rounded-md bg-[var(--card)]/40 backdrop-blur-sm text-[var(--foreground)] placeholder-[var(--muted-foreground)] focus:outline-none focus:ring-2 focus:ring-[var(--primary)]/50 focus:border-[var(--primary)]/50 focus:bg-[var(--card)]/60 transition-all duration-200"
            />
          </div>
        </div>
      </div>

      {/* Notes List */}
      <div className="flex-1 overflow-y-auto">
        {isLoading ? (
          <div className="p-4 text-center text-[var(--muted-foreground)]">
            Chargement des notes...
          </div>
        ) : filteredNotes.length === 0 ? (
          <div className="p-4 text-center text-[var(--muted-foreground)]">
            {searchQuery ? 'Aucune note trouvée' : 'Aucune note pour le moment'}
          </div>
        ) : (
          <DndContext
            sensors={sensors}
            collisionDetection={closestCenter}
            onDragEnd={handleDragEnd}
          >
            <div className="p-2 space-y-1">
              <SortableContext
                items={filteredNotes.map((n) => n.id)}
                strategy={verticalListSortingStrategy}
              >
                {filteredNotes.map((note) => (
                  <SortableNoteItem
                    key={note.id}
                    note={note}
                    isSelected={selectedNoteId === note.id}
                    onSelect={() => onSelectNote(note)}
                    onDelete={handleDeleteConfirm}
                    showDeleteConfirm={showDeleteConfirm}
                    setShowDeleteConfirm={setShowDeleteConfirm}
                  />
                ))}
              </SortableContext>
            </div>
          </DndContext>
        )}
      </div>
    </div>
  );
}
