import { useState, useEffect, useMemo, useRef } from 'react';
import { ChevronLeft, FileText, Plus, Search, Trash2, Loader2, Save, Calendar, Edit } from 'lucide-react';
import ReactQuill, { Quill } from 'react-quill-new'; // Nếu react-quill gặp lỗi với React 18, hãy dùng react-quill-new
import 'react-quill-new/dist/quill.snow.css';

// Cấu hình Lucide Icons cho Quill
const Icons = Quill.import('ui/icons') as any;
Icons['bold'] = '<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round"><path d="M6 4h8a4 4 0 0 1 4 4 4 4 0 0 1-4 4H6z"/><path d="M6 12h9a4 4 0 0 1 4 4 4 4 0 0 1-4 4H6z"/></svg>';
Icons['italic'] = '<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round"><line x1="19" y1="4" x2="10" y2="4"/><line x1="14" y1="20" x2="5" y2="20"/><line x1="15" y1="4" x2="9" y2="20"/></svg>';
Icons['underline'] = '<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round"><path d="M6 3v7a6 6 0 0 0 6 6 6 6 0 0 0 6-6V3"/><line x1="4" y1="21" x2="20" y2="21"/></svg>';
Icons['strike'] = '<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round"><path d="M16 4H9a3 3 0 0 0-2.83 4"/><path d="M14 12a4 4 0 0 1 0 8H6"/><line x1="4" y1="12" x2="20" y2="12"/></svg>';
Icons['link'] = '<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round"><path d="M10 13a5 5 0 0 0 7.54.54l3-3a5 5 0 0 0-7.07-7.07l-1.72 1.71"/><path d="M14 11a5 5 0 0 0-7.54-.54l-3 3a5 5 0 0 0 7.07 7.07l1.71-1.71"/></svg>';
Icons['image'] = '<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round"><rect x="3" y="3" width="18" height="18" rx="2" ry="2"/><circle cx="8.5" cy="8.5" r="1.5"/><polyline points="21 15 16 10 5 21"/></svg>';
Icons['clean'] = '<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round"><path d="m7 21-4.3-4.3c-1-1-1-2.5 0-3.4l9.9-9.9c1-1 2.5-1 3.4 0l4.4 4.4c1 1 1 2.5 0 3.4L11 21Z"/><path d="m22 21-5.9-5.9"/><path d="M16 11l-5 5"/></svg>';
Icons['table'] = '<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round"><path d="M3 3h18v18H3z"/><path d="M3 9h18"/><path d="M3 15h18"/><path d="M9 3v18"/><path d="M15 3v18"/></svg>';
Icons['header']['1'] = '<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round"><path d="M4 12h8"/><path d="M4 18V6"/><path d="M12 18V6"/><path d="m17 12 3-2v8"/></svg>';
Icons['header']['2'] = '<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round"><path d="M4 12h8"/><path d="M4 18V6"/><path d="M12 18V6"/><path d="M21 18h-4c0-4 4-3 4-6 0-1.5-2-2.5-4-1"/></svg>';
Icons['list']['bullet'] = '<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round"><line x1="8" y1="6" x2="21" y2="6"/><line x1="8" y1="12" x2="21" y2="12"/><line x1="8" y1="18" x2="21" y2="18"/><line x1="3" y1="6" x2="3.01" y2="6"/><line x1="3" y1="12" x2="3.01" y2="12"/><line x1="3" y1="18" x2="3.01" y2="18"/></svg>';
Icons['list']['check'] = '<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round"><rect x="3" y="3" width="18" height="18" rx="2"/><path d="m9 12 2 2 4-4"/></svg>';
Icons['align'][''] = '<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round"><line x1="17" y1="10" x2="3" y2="10"/><line x1="21" y1="6" x2="3" y2="6"/><line x1="21" y1="14" x2="3" y2="14"/><line x1="17" y1="18" x2="3" y2="18"/></svg>';
Icons['align']['center'] = '<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round"><line x1="18" y1="10" x2="6" y2="10"/><line x1="21" y1="6" x2="3" y2="6"/><line x1="21" y1="14" x2="3" y2="14"/><line x1="18" y1="18" x2="6" y2="18"/></svg>';
Icons['align']['right'] = '<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round"><line x1="21" y1="10" x2="7" y2="10"/><line x1="21" y1="6" x2="3" y2="6"/><line x1="21" y1="14" x2="3" y2="14"/><line x1="21" y1="18" x2="7" y2="18"/></svg>';
Icons['align']['justify'] = '<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round"><line x1="21" y1="10" x2="3" y2="10"/><line x1="21" y1="6" x2="3" y2="6"/><line x1="21" y1="14" x2="3" y2="14"/><line x1="21" y1="18" x2="3" y2="18"/></svg>';
Icons['indent']['+1'] = '<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round"><polyline points="11 17 16 12 11 7"/><line x1="18" y1="12" x2="3" y2="12"/></svg>';
Icons['indent']['-1'] = '<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round"><polyline points="8 17 3 12 8 7"/><line x1="21" y1="12" x2="6" y2="12"/></svg>';

interface Note {
  id: string;
  title: string;
  content: string;
  createdAt: string;
  synced?: boolean;
  deletedLocally?: boolean;
}

export const MyNotePage = ({ tourId, onBack }: { tourId: string; onBack: () => void }) => {
  const [isLoading, setIsLoading] = useState(false);
  const [notes, setNotes] = useState<Note[]>([]);
  const [isCreating, setIsCreating] = useState(false);
  const [searchQuery, setSearchQuery] = useState('');
  const [editingNoteId, setEditingNoteId] = useState<string | null>(null);
  
  const quillRef = useRef<ReactQuill>(null);

  // State cho form ghi chú
  const [noteForm, setNoteForm] = useState({ title: '', content: '' });

  const syncLocalNotesToServer = async (localNotes: Note[]) => {
    const updatedNotesList = [...localNotes];
    let hasChanges = false;

    // 1. Đồng bộ các ghi chú bị xóa offline
    const deletedNotes = localNotes.filter((n: any) => n.deletedLocally);
    for (const note of deletedNotes) {
      try {
        const res = await fetch(`/api/v1/tours/${tourId}/notes/${note.id}`, {
          method: 'DELETE',
          headers: {
            'Authorization': `Bearer ${localStorage.getItem('token')}`
          }
        });
        if (res.ok || res.status === 404) {
          const idx = updatedNotesList.findIndex(n => n.id === note.id);
          if (idx !== -1) {
            updatedNotesList.splice(idx, 1);
            hasChanges = true;
          }
        }
      } catch (err) {
        console.error("Lỗi đồng bộ xóa ghi chú:", err);
      }
    }

    // 2. Đồng bộ các ghi chú tạo mới offline
    const tempNotes = localNotes.filter(n => n.id.startsWith('temp_') && !(n as any).deletedLocally);
    for (const note of tempNotes) {
      try {
        const res = await fetch(`/api/v1/tours/${tourId}/notes`, {
          method: 'POST',
          headers: {
            'Content-Type': 'application/json',
            'Authorization': `Bearer ${localStorage.getItem('token')}`
          },
          body: JSON.stringify({
            title: note.title,
            content: note.content
          })
        });
        if (res.ok) {
          const savedNote = await res.json();
          const idx = updatedNotesList.findIndex(n => n.id === note.id);
          if (idx !== -1) {
            updatedNotesList[idx] = {
              ...savedNote,
              synced: true
            };
            hasChanges = true;
          }
        }
      } catch (err) {
        console.error("Lỗi đồng bộ tạo ghi chú mới:", err);
      }
    }

    // 3. Đồng bộ các ghi chú chỉnh sửa offline
    const editedNotes = localNotes.filter((n: any) => !n.id.startsWith('temp_') && n.synced === false && !n.deletedLocally);
    for (const note of editedNotes) {
      try {
        const res = await fetch(`/api/v1/tours/${tourId}/notes/${note.id}`, {
          method: 'PUT',
          headers: {
            'Content-Type': 'application/json',
            'Authorization': `Bearer ${localStorage.getItem('token')}`
          },
          body: JSON.stringify({
            title: note.title,
            content: note.content
          })
        });
        if (res.ok) {
          const updatedNote = await res.json();
          const idx = updatedNotesList.findIndex(n => n.id === note.id);
          if (idx !== -1) {
            updatedNotesList[idx] = {
              ...updatedNote,
              synced: true
            };
            hasChanges = true;
          }
        }
      } catch (err) {
        console.error("Lỗi đồng bộ cập nhật ghi chú:", err);
      }
    }

    return { updatedNotesList, hasChanges };
  };

  const fetchServerNotes = async (currentLocalNotes: Note[]) => {
    setIsLoading(true);
    try {
      const { updatedNotesList, hasChanges } = await syncLocalNotesToServer(currentLocalNotes);
      let mergedNotes = updatedNotesList;

      const res = await fetch(`/api/v1/tours/${tourId}/notes`, {
        headers: {
          'Authorization': `Bearer ${localStorage.getItem('token')}`
        }
      });
      if (res.ok) {
        const serverNotes = await res.json();
        if (Array.isArray(serverNotes)) {
          const unsyncedNotes = mergedNotes.filter((n: any) => n.synced === false || n.id.startsWith('temp_') || n.deletedLocally);
          const serverNotesFiltered = serverNotes.filter(sn => !unsyncedNotes.some(un => un.id === sn.id));
          const finalNotes = [...unsyncedNotes, ...serverNotesFiltered].sort(
            (a, b) => new Date(b.createdAt).getTime() - new Date(a.createdAt).getTime()
          );

          setNotes(finalNotes);
          localStorage.setItem(`my_journey_notes_${tourId}`, JSON.stringify(finalNotes));
          setIsLoading(false);
          return;
        }
      }
      
      if (hasChanges) {
        setNotes(mergedNotes);
        localStorage.setItem(`my_journey_notes_${tourId}`, JSON.stringify(mergedNotes));
      }
    } catch (e) {
      console.warn("Offline or backend fetch failed, using local storage cache:", e);
    } finally {
      setIsLoading(false);
    }
  };

  // Khôi phục ghi chú từ localStorage khi load trang
  useEffect(() => {
    let initialNotes: Note[] = [];
    const saved = localStorage.getItem(`my_journey_notes_${tourId}`);
    if (saved) {
      try { 
        const parsed = JSON.parse(saved);
        if (Array.isArray(parsed)) {
          initialNotes = parsed;
          setNotes(parsed);
        }
      } catch (e) { console.error("Lỗi parse notes:", e); }
    }
    fetchServerNotes(initialNotes);
  }, [tourId]);

  // Tự động lưu ghi chú vào localStorage khi có thay đổi
  useEffect(() => {
    localStorage.setItem(`my_journey_notes_${tourId}`, JSON.stringify(notes));
  }, [notes, tourId]);

  // Cấu hình các công cụ định dạng cho ReactQuill
  const quillModules = useMemo(() => ({
    table: true,
    toolbar: {
      container: [
        [{ 'header': 1 }, { 'header': 2 }],
        ['bold', 'italic', 'underline', 'strike'],
        [{ 'align': [] }],
        [{ 'indent': '-1'}, { 'indent': '+1' }],
        [{ 'list': 'bullet' }, { 'list': 'check' }],
        ['link', 'image', 'table', 'clean'],
      ],
      handlers: {
        table: function() {
          const rows = prompt('Nhập số hàng:', '3');
          const cols = prompt('Nhập số cột:', '3');
          if (rows && cols) {
            const quill = (quillRef.current as any)?.getEditor();
            if (quill) {
              quill.getModule('table').insertTable(parseInt(rows), parseInt(cols));
            }
          }
        }
      }
    },
  }), []);

  const handleSaveNote = async () => {
    if (!noteForm.title.trim() && !noteForm.content.trim()) return;

    if (editingNoteId) {
      const updatedNotes = notes.map(n => n.id === editingNoteId ? {
        ...n,
        title: noteForm.title || 'Ghi chú không tiêu đề',
        content: noteForm.content,
        createdAt: new Date().toISOString(),
        synced: false
      } : n);
      
      setNotes(updatedNotes);
      setIsCreating(false);
      const targetId = editingNoteId;
      setEditingNoteId(null);
      setNoteForm({ title: '', content: '' });

      // Sync to backend
      try {
        const res = await fetch(`/api/v1/tours/${tourId}/notes/${targetId}`, {
          method: 'PUT',
          headers: {
            'Content-Type': 'application/json',
            'Authorization': `Bearer ${localStorage.getItem('token')}`
          },
          body: JSON.stringify({
            title: noteForm.title || 'Ghi chú không tiêu đề',
            content: noteForm.content
          })
        });
        if (res.ok) {
          const updatedNote = await res.json();
          setNotes(prev => prev.map(n => n.id === targetId ? { ...updatedNote, synced: true } : n));
        }
      } catch (err) {
        console.error("Lỗi đồng bộ cập nhật ghi chú:", err);
      }
    } else {
      const tempId = `temp_${Date.now()}`;
      const note: Note = {
        id: tempId,
        title: noteForm.title || 'Ghi chú không tiêu đề',
        content: noteForm.content,
        createdAt: new Date().toISOString(),
        synced: false
      };

      setNotes([note, ...notes]);
      setIsCreating(false);
      setNoteForm({ title: '', content: '' });

      // Sync to backend
      try {
        const res = await fetch(`/api/v1/tours/${tourId}/notes`, {
          method: 'POST',
          headers: {
            'Content-Type': 'application/json',
            'Authorization': `Bearer ${localStorage.getItem('token')}`
          },
          body: JSON.stringify({
            title: note.title,
            content: note.content
          })
        });
        if (res.ok) {
          const savedNote = await res.json();
          setNotes(prev => prev.map(n => n.id === tempId ? { ...savedNote, synced: true } : n));
        }
      } catch (err) {
        console.error("Lỗi đồng bộ ghi chú mới:", err);
      }
    }
  };

  const handleEditNote = (note: Note) => {
    setNoteForm({ title: note.title, content: note.content });
    setEditingNoteId(note.id);
    setIsCreating(true);
  };

  const handleDeleteNote = async (id: string) => {
    if (window.confirm("Bạn có chắc chắn muốn xóa ghi chú này?")) {
      if (id.startsWith('temp_')) {
        setNotes(prev => prev.filter(n => n.id !== id));
        return;
      }

      setNotes(prev => prev.map(n => n.id === id ? { ...n, deletedLocally: true } : n));
      
      try {
        const res = await fetch(`/api/v1/tours/${tourId}/notes/${id}`, {
          method: 'DELETE',
          headers: {
            'Authorization': `Bearer ${localStorage.getItem('token')}`
          }
        });
        if (res.ok || res.status === 404) {
          setNotes(prev => prev.filter(n => n.id !== id));
        }
      } catch (err) {
        console.error("Lỗi đồng bộ xóa ghi chú:", err);
      }
    }
  };

  const filteredNotes = (notes || [])
    .filter((n: any) => !n.deletedLocally)
    .filter(n => {
      const title = (n.title || '').toLowerCase();
      const content = (n.content || '').replace(/<[^>]*>/g, '').toLowerCase();
      const query = searchQuery.toLowerCase();
      
      return title.includes(query) || content.includes(query);
    });

  return (
    <div className="min-h-screen bg-[var(--background)] flex flex-col">
      {/* Header */}
      <div className="sticky top-0 z-30 bg-[var(--surface)]/80 backdrop-blur-md border-b border-[var(--border)] px-4 py-4 flex items-center gap-4">
        <button onClick={onBack} className="p-2 hover:bg-[var(--background)] rounded-full transition-colors">
          <ChevronLeft className="w-6 h-6 text-[var(--text-secondary)]" />
        </button>
        <div>
          <h1 className="text-xl font-black text-[var(--text-primary)]">Ghi chú của tôi</h1>
          <p className="text-[10px] font-bold text-[var(--text-muted)] uppercase tracking-widest">Sổ tay hành trình cá nhân</p>
        </div>
      </div>

      <div className="flex-1 p-6 max-w-2xl mx-auto w-full">
        {!isCreating && (
          <div className="flex items-center gap-4 mb-8">
            <div className="relative flex-1">
            <input
              type="text"
              placeholder="Tìm kiếm nội dung ghi chú..."
              className="w-full pl-10 pr-4 py-3 bg-[var(--surface)] dark:bg-[var(--background-alt)] rounded-2xl border border-[var(--border)] dark:border-[var(--border)] shadow-sm focus:ring-2 focus:ring-amber-500 outline-none transition-all text-sm text-[var(--text-primary)] dark:text-[var(--text-primary)] placeholder-[var(--text-muted)]"
              value={searchQuery}
              onChange={(e) => setSearchQuery(e.target.value)}
            />
            <Search className="absolute left-3.5 top-1/2 -translate-y-1/2 w-4 h-4 text-[var(--text-muted)]" />
          </div>
          <button 
            onClick={() => setIsCreating(true)}
            className="p-3 bg-amber-500 text-white rounded-2xl shadow-lg shadow-amber-200 hover:bg-amber-600 transition-all active:scale-95"
          >
            <Plus className="w-6 h-6" />
          </button>
        </div>
        )}

        {isLoading ? (
          <div className="flex flex-col items-center justify-center py-20 text-[var(--text-muted)]">
            <Loader2 className="w-10 h-10 animate-spin mb-4" />
            <p className="font-bold">Đang tải ghi chú...</p>
          </div>
        ) : isCreating ? (
          <div className="space-y-4 animate-in fade-in slide-in-from-bottom-4">
            <input
              type="text"
              placeholder="Tiêu đề ghi chú..."
              className="w-full px-4 py-3 bg-[var(--surface)] rounded-2xl border border-[var(--border)] shadow-sm focus:ring-2 focus:ring-amber-500 outline-none transition-all text-lg font-bold"
              value={noteForm.title}
              onChange={(e) => setNoteForm({ ...noteForm, title: e.target.value })}
            />
            <div className="bg-[var(--surface)] rounded-2xl border border-[var(--border)] shadow-sm overflow-hidden min-h-[500px] flex flex-col h-full">
              <ReactQuill 
                ref={quillRef}
                theme="snow" 
                value={noteForm.content} 
                onChange={(content) => setNoteForm({ ...noteForm, content })}
                modules={quillModules}
                placeholder="Bắt đầu viết cảm nhận của bạn tại đây..."
                  className="flex-1 flex flex-col [&_.ql-container]:flex-1 [&_.ql-container]:flex [&_.ql-container]:flex-col [&_.ql-container]:h-full [&_.ql-container]:min-h-0 [&_.ql-editor]:flex-1 [&_.ql-editor]:overflow-y-auto [&_.ql-editor]:text-base [&_.ql-toolbar]:flex [&_.ql-toolbar]:flex-wrap sm:[&_.ql-toolbar]:flex-nowrap [&_.ql-toolbar]:border-0 [&_.ql-toolbar]:border-b [&_.ql-toolbar]:border-[var(--border)] [&_.ql-editor_table]:border-collapse [&_.ql-editor_table]:w-full [&_.ql-editor_td]:border [&_.ql-editor_td]:border-[var(--border)] [&_.ql-editor_td]:p-2 [&_.ql-editor_.ql-align-center]:text-center [&_.ql-editor_.ql-align-right]:text-right [&_.ql-editor_.ql-align-justify]:text-justify [&_.ql-picker-options]:!z-[50] [&_.ql-picker-options]:!shadow-xl [&_.ql-picker-options]:!rounded-xl [&_.ql-picker-options]:!border-[var(--border)] [&_.ql-stroke]:!stroke-[var(--text-secondary)] [&_.ql-fill]:!fill-[var(--text-secondary)] [&_button:hover_.ql-stroke]:!stroke-amber-500 [&_button:hover_.ql-fill]:!stroke-amber-500 [&_button.ql-active_.ql-stroke]:!stroke-amber-500"
              />
            </div>
            <div className="flex gap-3">
              <button 
                onClick={handleSaveNote}
                className="flex-1 flex items-center justify-center gap-2 bg-amber-500 hover:bg-amber-600 text-white py-4 rounded-2xl font-black uppercase tracking-widest text-xs transition-all shadow-lg shadow-amber-200"
              >
                <Save className="w-5 h-5" /> Lưu ghi chú
              </button>
              <button 
                onClick={() => { setIsCreating(false); setNoteForm({ title: '', content: '' }); }}
                className="px-6 py-4 bg-gray-100 hover:bg-gray-200 text-gray-500 rounded-2xl font-black uppercase tracking-widest text-xs transition-all"
              >
                Hủy
              </button>
            </div>
          </div>
        ) : filteredNotes.length > 0 ? (
          <div className="grid grid-cols-1 gap-4">
            {filteredNotes.map((note) => (
              <div key={note.id} className="bg-[var(--surface)] dark:bg-[var(--surface-muted)] p-5 rounded-3xl border border-[var(--border)] dark:border-[var(--border)] shadow-sm hover:shadow-md transition-all group">
                <div className="flex justify-between items-start mb-3">
                  <div>
                    <h4 className="font-bold text-[var(--text-primary)] dark:text-[var(--text-primary)]">{note.title}</h4>
                    <div className="flex items-center gap-2 text-[10px] text-[var(--text-muted)] dark:text-[var(--text-muted)] font-bold uppercase mt-1">
                      <Calendar className="w-3 h-3" />
                      {new Date(note.createdAt).toLocaleDateString("vi-VN")}
                    </div>
                  </div>
                  <div className="flex gap-1">
                    <button 
                      onClick={() => handleEditNote(note)}
                      className="p-2 text-[var(--text-muted)] dark:text-[var(--text-muted)] hover:text-blue-500 hover:bg-[var(--background)] dark:hover:bg-[var(--background)] rounded-xl transition-all opacity-0 group-hover:opacity-100"
                      title="Sửa ghi chú"
                    >
                      <Edit className="w-4 h-4" />
                    </button>
                    <button 
                      onClick={() => handleDeleteNote(note.id)}
                      className="p-2 text-[var(--text-muted)] dark:text-[var(--text-muted)] hover:text-red-500 hover:bg-[var(--background)] dark:hover:bg-[var(--background)] rounded-xl transition-all opacity-0 group-hover:opacity-100"
                      title="Xóa ghi chú"
                    >
                      <Trash2 className="w-4 h-4" />
                    </button>
                  </div>
                </div>
                <div 
                  className="text-sm text-[var(--text-secondary)] dark:text-[var(--text-secondary)] prose prose-sm max-w-none overflow-y-auto max-h-[280px] pr-1 [&_h2]:text-base [&_h2]:font-bold [&_h2]:mt-3 [&_h2]:mb-2 [&_h2]:text-[var(--text-primary)] [&_h4]:text-sm [&_h4]:font-bold [&_h4]:mt-2 [&_h4]:mb-1 [&_h4]:text-[var(--text-primary)] [&_ul]:list-disc [&_ul]:pl-5 [&_ul]:my-2 [&_li]:mb-1 [&_p]:mb-2 [&_p]:break-words"
                  dangerouslySetInnerHTML={{ __html: note.content }}
                />
              </div>
            ))}
          </div>
        ) : (
            <div className="text-center py-24 bg-[var(--surface)] dark:bg-[var(--background-alt)] rounded-[40px] border-2 border-dashed border-[var(--border)] dark:border-[var(--border)] shadow-inner">
              <div className="w-20 h-20 bg-amber-50 rounded-3xl flex items-center justify-center mx-auto mb-6 text-amber-500">
                <FileText className="w-10 h-10" />
              </div>
              <h3 className="text-xl font-bold text-gray-900 dark:text-white">{searchQuery ? 'Không tìm thấy ghi chú' : 'Chưa có ghi chú nào'}</h3>
              <p className="text-sm text-gray-400 dark:text-slate-400 max-w-xs mx-auto mt-2">
                {searchQuery ? 'Hãy thử tìm kiếm với từ khóa khác.' : 'Hãy lưu lại những cảm nhận, lịch trình riêng hoặc các lưu ý quan trọng cho hành trình của bạn.'}
              </p>
              {!searchQuery && (
              <button 
                onClick={() => setIsCreating(true)}
                className="mt-8 inline-flex items-center gap-2 bg-amber-500 hover:bg-amber-600 text-white px-8 py-4 rounded-2xl font-black uppercase tracking-widest text-xs transition-all shadow-lg shadow-amber-200 active:scale-95"
              >
                <Plus className="w-5 h-5" /> Tạo ghi chú mới
              </button>
              )}
            </div>
        )}
      </div>
    </div>
  );
};