// ContactNotesTab.tsx
import React, { useState, useMemo, useRef, useEffect } from 'react';
import { format, formatDistanceToNow, isToday, isYesterday } from 'date-fns';
import {
    Plus,
    Edit3,
    Trash2,
    Loader2,
    X,
    Check,
    Search,
    StickyNote,
    Pin,
    PinOff,
    Copy,
    MoreHorizontal,
    Clock,
    Calendar,
    Hash,
    Sparkles,
    FileText,
    ChevronDown,
    Star,
    StarOff,
    Maximize2,
    Minimize2,
    MessageSquare,
    Tag,
    Filter,
    SortDesc,
    SortAsc,
    LayoutGrid,
    LayoutList,
    Eye,
    EyeOff,
} from 'lucide-react';
import { Button } from '@/components/ui/button';
import { Textarea } from '@/components/ui/textarea';
import { Input } from '@/components/ui/input';
import { Card, CardContent } from '@/components/ui/card';
import { Badge } from '@/components/ui/badge';
import { Label } from '@/components/ui/label';
import { Separator } from '@/components/ui/separator';
import { ScrollArea } from '@/components/ui/scroll-area';
import {
    Dialog,
    DialogContent,
    DialogDescription,
    DialogFooter,
    DialogHeader,
    DialogTitle,
} from '@/components/ui/dialog';
import {
    DropdownMenu,
    DropdownMenuContent,
    DropdownMenuItem,
    DropdownMenuSeparator,
    DropdownMenuTrigger,
    DropdownMenuRadioGroup,
    DropdownMenuRadioItem,
    DropdownMenuLabel,
    DropdownMenuCheckboxItem,
} from '@/components/ui/dropdown-menu';
import {
    Tooltip,
    TooltipContent,
    TooltipProvider,
    TooltipTrigger,
} from '@/components/ui/tooltip';
import {
    AlertDialog,
    AlertDialogAction,
    AlertDialogCancel,
    AlertDialogContent,
    AlertDialogDescription,
    AlertDialogFooter,
    AlertDialogHeader,
    AlertDialogTitle,
} from '@/components/ui/alert-dialog';
import {
    Popover,
    PopoverContent,
    PopoverTrigger,
} from '@/components/ui/popover';
import {
    Collapsible,
    CollapsibleContent,
    CollapsibleTrigger,
} from '@/components/ui/collapsible';
import { useContactNotes, Note } from '@/hooks/useContactNotes';
import { cn } from '@/lib/utils';
import { toast } from 'sonner';

interface ContactNotesTabProps {
    contactId: string;
    maxHeight?: string;
}

type SortOption = 'newest' | 'oldest' | 'updated' | 'pinned';
type ViewMode = 'list' | 'compact';

// Note colors/categories
const noteColors = [
    { id: 'default', label: 'Default', class: 'bg-card border-border' },
    { id: 'yellow', label: 'Yellow', class: 'bg-yellow-50 border-yellow-200 dark:bg-yellow-950/30 dark:border-yellow-800' },
    { id: 'green', label: 'Green', class: 'bg-green-50 border-green-200 dark:bg-green-950/30 dark:border-green-800' },
    { id: 'blue', label: 'Blue', class: 'bg-blue-50 border-blue-200 dark:bg-blue-950/30 dark:border-blue-800' },
    { id: 'purple', label: 'Purple', class: 'bg-purple-50 border-purple-200 dark:bg-purple-950/30 dark:border-purple-800' },
    { id: 'pink', label: 'Pink', class: 'bg-pink-50 border-pink-200 dark:bg-pink-950/30 dark:border-pink-800' },
];

// Quick templates
const noteTemplates = [
    { label: 'Meeting Notes', content: '📅 Meeting Notes\n\nDate: \nAttendees: \n\nDiscussion Points:\n• \n\nAction Items:\n• \n\nNext Steps:\n' },
    { label: 'Call Summary', content: '📞 Call Summary\n\nDuration: \nTopic: \n\nKey Points:\n• \n\nFollow-up Required:\n' },
    { label: 'Important Info', content: '⚠️ Important Information\n\n\n\nSource:\nDate Recorded: ' },
    { label: 'Decision Made', content: '✅ Decision Record\n\nDecision: \nReason: \nDate: \n\nImplications:\n• ' },
];

function formatNoteDate(dateStr: string): string {
    const date = new Date(dateStr);
    if (isToday(date)) {
        return `Today at ${format(date, 'h:mm a')}`;
    }
    if (isYesterday(date)) {
        return `Yesterday at ${format(date, 'h:mm a')}`;
    }
    return format(date, "MMM d, yyyy 'at' h:mm a");
}

function extractPreview(content: string, maxLength: number = 150): string {
    const firstLine = content.split('\n')[0];
    if (firstLine.length <= maxLength) return firstLine;
    return firstLine.substring(0, maxLength) + '...';
}

function countWords(text: string): number {
    return text.trim().split(/\s+/).filter(Boolean).length;
}

export function ContactNotesTab({ contactId, maxHeight = '500px' }: ContactNotesTabProps) {
    const {
        notes,
        isLoading,
        createNote,
        updateNote,
        deleteNote,
        isCreating,
        isUpdating,
        isDeleting,
    } = useContactNotes(contactId);

    // State
    const [isComposeOpen, setIsComposeOpen] = useState(false);
    const [composeContent, setComposeContent] = useState('');
    const [composeColor, setComposeColor] = useState('default');
    const [composePinned, setComposePinned] = useState(false);

    const [editingNote, setEditingNote] = useState<Note | null>(null);
    const [editContent, setEditContent] = useState('');
    const [editColor, setEditColor] = useState('default');

    const [expandedNoteId, setExpandedNoteId] = useState<string | null>(null);
    const [deletingNoteId, setDeletingNoteId] = useState<string | null>(null);

    // Filters & View
    const [searchQuery, setSearchQuery] = useState('');
    const [sortBy, setSortBy] = useState<SortOption>('newest');
    const [viewMode, setViewMode] = useState<ViewMode>('list');
    const [showPinnedOnly, setShowPinnedOnly] = useState(false);

    const textareaRef = useRef<HTMLTextAreaElement>(null);

    // Focus textarea when compose opens
    useEffect(() => {
        if (isComposeOpen && textareaRef.current) {
            textareaRef.current.focus();
        }
    }, [isComposeOpen]);

    // Reset compose form
    const resetCompose = () => {
        setComposeContent('');
        setComposeColor('default');
        setComposePinned(false);
    };

    // Handle create
    const handleCreate = async () => {
        if (!composeContent.trim()) return;

        await createNote(composeContent.trim());
        toast.success('Note created');
        setIsComposeOpen(false);
        resetCompose();
    };

    // Handle update
    const handleUpdate = async () => {
        if (!editingNote || !editContent.trim()) return;

        await updateNote({ noteId: editingNote.id, content: editContent.trim() });
        toast.success('Note updated');
        setEditingNote(null);
        setEditContent('');
    };

    // Handle delete
    const handleDelete = async () => {
        if (!deletingNoteId) return;

        const noteToDelete = notes.find((n) => n.id === deletingNoteId);
        await deleteNote(deletingNoteId);

        toast.success('Note deleted', {
            action: noteToDelete
                ? {
                    label: 'Undo',
                    onClick: () => createNote(noteToDelete.content),
                }
                : undefined,
        });

        setDeletingNoteId(null);
    };

    // Copy note
    const copyNote = (note: Note) => {
        navigator.clipboard.writeText(note.content);
        toast.success('Copied to clipboard');
    };

    // Apply template
    const applyTemplate = (template: string) => {
        setComposeContent(template);
    };

    // Open edit dialog
    const openEdit = (note: Note) => {
        setEditingNote(note);
        setEditContent(note.content);
        setEditColor('default');
    };

    // Filtered and sorted notes
    const filteredNotes = useMemo(() => {
        let result = [...notes];

        // Search filter
        if (searchQuery.trim()) {
            const query = searchQuery.toLowerCase();
            result = result.filter((note) =>
                note.content.toLowerCase().includes(query)
            );
        }

        // Pinned only filter (simulated - you'd need to add pinned field to your Note type)
        // if (showPinnedOnly) {
        //   result = result.filter((note) => note.pinned);
        // }

        // Sort
        switch (sortBy) {
            case 'newest':
                result.sort((a, b) => new Date(b.created_at).getTime() - new Date(a.created_at).getTime());
                break;
            case 'oldest':
                result.sort((a, b) => new Date(a.created_at).getTime() - new Date(b.created_at).getTime());
                break;
            case 'updated':
                result.sort((a, b) => new Date(b.updated_at).getTime() - new Date(a.updated_at).getTime());
                break;
            // case 'pinned':
            //   result.sort((a, b) => (b.pinned ? 1 : 0) - (a.pinned ? 1 : 0));
            //   break;
        }

        return result;
    }, [notes, searchQuery, sortBy, showPinnedOnly]);

    // Stats
    const stats = useMemo(() => {
        const totalWords = notes.reduce((acc, note) => acc + countWords(note.content), 0);
        const totalChars = notes.reduce((acc, note) => acc + note.content.length, 0);
        return {
            count: notes.length,
            words: totalWords,
            chars: totalChars,
        };
    }, [notes]);

    if (isLoading) {
        return (
            <div className="flex items-center justify-center h-48">
                <div className="flex flex-col items-center gap-2">
                    <Loader2 className="h-6 w-6 animate-spin text-muted-foreground" />
                    <span className="text-sm text-muted-foreground">Loading notes...</span>
                </div>
            </div>
        );
    }

    return (
        <div className="flex flex-col h-full">
            {/* Header */}
            <div className="flex-shrink-0 space-y-3 pb-4">
                {/* Title Row */}
                <div className="flex items-center justify-between">
                    <div className="flex items-center gap-3">
                        <div className="h-9 w-9 rounded-lg bg-amber-500/10 flex items-center justify-center">
                            <StickyNote className="h-5 w-5 text-amber-600" />
                        </div>
                        <div>
                            <h3 className="text-base font-semibold">Notes</h3>
                            <p className="text-xs text-muted-foreground">
                                {stats.count} notes · {stats.words.toLocaleString()} words
                            </p>
                        </div>
                    </div>

                    <Button
                        size="sm"
                        onClick={() => setIsComposeOpen(true)}
                        className="gap-2"
                    >
                        <Plus className="h-4 w-4" />
                        New Note
                    </Button>
                </div>

                {/* Search & Controls */}
                {notes.length > 0 && (
                    <div className="flex items-center gap-2">
                        {/* Search */}
                        <div className="relative flex-1">
                            <Search className="h-4 w-4 text-muted-foreground absolute left-2.5 top-1/2 -translate-y-1/2" />
                            <Input
                                value={searchQuery}
                                onChange={(e) => setSearchQuery(e.target.value)}
                                placeholder="Search notes..."
                                className="pl-8 h-8 text-sm"
                            />
                            {searchQuery && (
                                <Button
                                    variant="ghost"
                                    size="sm"
                                    className="h-6 w-6 p-0 absolute right-1 top-1/2 -translate-y-1/2"
                                    onClick={() => setSearchQuery('')}
                                >
                                    <X className="h-3.5 w-3.5" />
                                </Button>
                            )}
                        </div>

                        {/* Sort */}
                        <DropdownMenu>
                            <DropdownMenuTrigger asChild>
                                <Button variant="outline" size="sm" className="h-8 gap-1.5 text-xs">
                                    {sortBy === 'newest' || sortBy === 'updated' ? (
                                        <SortDesc className="h-3.5 w-3.5" />
                                    ) : (
                                        <SortAsc className="h-3.5 w-3.5" />
                                    )}
                                    Sort
                                </Button>
                            </DropdownMenuTrigger>
                            <DropdownMenuContent align="end">
                                <DropdownMenuRadioGroup value={sortBy} onValueChange={(v) => setSortBy(v as SortOption)}>
                                    <DropdownMenuRadioItem value="newest">Newest First</DropdownMenuRadioItem>
                                    <DropdownMenuRadioItem value="oldest">Oldest First</DropdownMenuRadioItem>
                                    <DropdownMenuRadioItem value="updated">Recently Updated</DropdownMenuRadioItem>
                                </DropdownMenuRadioGroup>
                            </DropdownMenuContent>
                        </DropdownMenu>

                        {/* View Toggle */}
                        <div className="flex items-center border rounded-md">
                            <TooltipProvider>
                                <Tooltip>
                                    <TooltipTrigger asChild>
                                        <Button
                                            variant={viewMode === 'list' ? 'secondary' : 'ghost'}
                                            size="sm"
                                            className="h-8 w-8 p-0 rounded-r-none"
                                            onClick={() => setViewMode('list')}
                                        >
                                            <LayoutList className="h-3.5 w-3.5" />
                                        </Button>
                                    </TooltipTrigger>
                                    <TooltipContent>List View</TooltipContent>
                                </Tooltip>
                            </TooltipProvider>

                            <TooltipProvider>
                                <Tooltip>
                                    <TooltipTrigger asChild>
                                        <Button
                                            variant={viewMode === 'compact' ? 'secondary' : 'ghost'}
                                            size="sm"
                                            className="h-8 w-8 p-0 rounded-l-none"
                                            onClick={() => setViewMode('compact')}
                                        >
                                            <LayoutGrid className="h-3.5 w-3.5" />
                                        </Button>
                                    </TooltipTrigger>
                                    <TooltipContent>Compact View</TooltipContent>
                                </Tooltip>
                            </TooltipProvider>
                        </div>
                    </div>
                )}
            </div>

            {/* Notes List */}
            <ScrollArea className="flex-1" style={{ maxHeight }}>
                <div className="pr-4 space-y-3 pb-4">
                    {filteredNotes.length === 0 ? (
                        <Card className="border-dashed">
                            <CardContent className="py-12 text-center">
                                <div className="mx-auto mb-4 h-12 w-12 rounded-full bg-muted flex items-center justify-center">
                                    {searchQuery ? (
                                        <Search className="h-6 w-6 text-muted-foreground" />
                                    ) : (
                                        <Sparkles className="h-6 w-6 text-muted-foreground" />
                                    )}
                                </div>
                                <h4 className="font-medium mb-1">
                                    {searchQuery ? 'No matching notes' : 'No notes yet'}
                                </h4>
                                <p className="text-sm text-muted-foreground mb-4">
                                    {searchQuery
                                        ? 'Try a different search term'
                                        : 'Capture important information about this contact'}
                                </p>
                                {searchQuery ? (
                                    <Button variant="outline" size="sm" onClick={() => setSearchQuery('')}>
                                        Clear Search
                                    </Button>
                                ) : (
                                    <Button size="sm" onClick={() => setIsComposeOpen(true)} className="gap-2">
                                        <Plus className="h-4 w-4" />
                                        Create First Note
                                    </Button>
                                )}
                            </CardContent>
                        </Card>
                    ) : viewMode === 'list' ? (
                        // List View
                        filteredNotes.map((note) => {
                            const isExpanded = expandedNoteId === note.id;
                            const isLong = note.content.length > 300;
                            const wasEdited = note.updated_at !== note.created_at;

                            return (
                                <Card
                                    key={note.id}
                                    className={cn(
                                        "group transition-all hover:shadow-sm",
                                        "bg-card/50 hover:bg-card"
                                    )}
                                >
                                    <CardContent className="p-4">
                                        <div className="flex items-start gap-3">
                                            {/* Content */}
                                            <div className="flex-1 min-w-0">
                                                {/* Note Text */}
                                                <div
                                                    className={cn(
                                                        "text-sm whitespace-pre-wrap break-words",
                                                        !isExpanded && isLong && "line-clamp-4"
                                                    )}
                                                >
                                                    {note.content}
                                                </div>

                                                {/* Expand/Collapse for long notes */}
                                                {isLong && (
                                                    <Button
                                                        variant="ghost"
                                                        size="sm"
                                                        className="h-6 px-2 mt-2 text-xs text-muted-foreground"
                                                        onClick={() => setExpandedNoteId(isExpanded ? null : note.id)}
                                                    >
                                                        {isExpanded ? (
                                                            <>
                                                                <Minimize2 className="h-3 w-3 mr-1" />
                                                                Show less
                                                            </>
                                                        ) : (
                                                            <>
                                                                <Maximize2 className="h-3 w-3 mr-1" />
                                                                Show more
                                                            </>
                                                        )}
                                                    </Button>
                                                )}

                                                {/* Metadata */}
                                                <div className="flex items-center gap-3 mt-3 text-xs text-muted-foreground">
                                                    <span className="flex items-center gap-1">
                                                        <Clock className="h-3 w-3" />
                                                        {formatNoteDate(note.created_at)}
                                                    </span>
                                                    {wasEdited && (
                                                        <span className="flex items-center gap-1">
                                                            <Edit3 className="h-3 w-3" />
                                                            Edited {formatDistanceToNow(new Date(note.updated_at), { addSuffix: true })}
                                                        </span>
                                                    )}
                                                    <span className="flex items-center gap-1">
                                                        <Hash className="h-3 w-3" />
                                                        {countWords(note.content)} words
                                                    </span>
                                                </div>
                                            </div>

                                            {/* Actions */}
                                            <div className="flex items-center gap-1 opacity-0 group-hover:opacity-100 transition-opacity">
                                                <TooltipProvider>
                                                    <Tooltip>
                                                        <TooltipTrigger asChild>
                                                            <Button
                                                                variant="ghost"
                                                                size="sm"
                                                                className="h-7 w-7 p-0"
                                                                onClick={() => copyNote(note)}
                                                            >
                                                                <Copy className="h-3.5 w-3.5" />
                                                            </Button>
                                                        </TooltipTrigger>
                                                        <TooltipContent>Copy</TooltipContent>
                                                    </Tooltip>
                                                </TooltipProvider>

                                                <TooltipProvider>
                                                    <Tooltip>
                                                        <TooltipTrigger asChild>
                                                            <Button
                                                                variant="ghost"
                                                                size="sm"
                                                                className="h-7 w-7 p-0"
                                                                onClick={() => openEdit(note)}
                                                            >
                                                                <Edit3 className="h-3.5 w-3.5" />
                                                            </Button>
                                                        </TooltipTrigger>
                                                        <TooltipContent>Edit</TooltipContent>
                                                    </Tooltip>
                                                </TooltipProvider>

                                                <DropdownMenu>
                                                    <DropdownMenuTrigger asChild>
                                                        <Button variant="ghost" size="sm" className="h-7 w-7 p-0">
                                                            <MoreHorizontal className="h-3.5 w-3.5" />
                                                        </Button>
                                                    </DropdownMenuTrigger>
                                                    <DropdownMenuContent align="end" className="w-40">
                                                        <DropdownMenuItem onClick={() => copyNote(note)}>
                                                            <Copy className="h-4 w-4 mr-2" />
                                                            Copy
                                                        </DropdownMenuItem>
                                                        <DropdownMenuItem onClick={() => openEdit(note)}>
                                                            <Edit3 className="h-4 w-4 mr-2" />
                                                            Edit
                                                        </DropdownMenuItem>
                                                        <DropdownMenuSeparator />
                                                        <DropdownMenuItem
                                                            className="text-destructive focus:text-destructive"
                                                            onClick={() => setDeletingNoteId(note.id)}
                                                        >
                                                            <Trash2 className="h-4 w-4 mr-2" />
                                                            Delete
                                                        </DropdownMenuItem>
                                                    </DropdownMenuContent>
                                                </DropdownMenu>
                                            </div>
                                        </div>
                                    </CardContent>
                                </Card>
                            );
                        })
                    ) : (
                        // Compact Grid View
                        <div className="grid grid-cols-2 gap-3">
                            {filteredNotes.map((note) => (
                                <Card
                                    key={note.id}
                                    className="group cursor-pointer hover:shadow-sm transition-all bg-card/50 hover:bg-card"
                                    onClick={() => openEdit(note)}
                                >
                                    <CardContent className="p-3">
                                        <p className="text-xs line-clamp-4 whitespace-pre-wrap mb-2">
                                            {note.content}
                                        </p>
                                        <div className="flex items-center justify-between">
                                            <span className="text-[10px] text-muted-foreground">
                                                {format(new Date(note.created_at), 'MMM d')}
                                            </span>
                                            <div className="flex items-center gap-1 opacity-0 group-hover:opacity-100 transition-opacity">
                                                <Button
                                                    variant="ghost"
                                                    size="sm"
                                                    className="h-5 w-5 p-0"
                                                    onClick={(e) => {
                                                        e.stopPropagation();
                                                        copyNote(note);
                                                    }}
                                                >
                                                    <Copy className="h-3 w-3" />
                                                </Button>
                                                <Button
                                                    variant="ghost"
                                                    size="sm"
                                                    className="h-5 w-5 p-0 text-destructive"
                                                    onClick={(e) => {
                                                        e.stopPropagation();
                                                        setDeletingNoteId(note.id);
                                                    }}
                                                >
                                                    <Trash2 className="h-3 w-3" />
                                                </Button>
                                            </div>
                                        </div>
                                    </CardContent>
                                </Card>
                            ))}
                        </div>
                    )}
                </div>
            </ScrollArea>

            {/* Compose Note Dialog */}
            <Dialog open={isComposeOpen} onOpenChange={setIsComposeOpen}>
                <DialogContent className="sm:max-w-xl">
                    <DialogHeader>
                        <DialogTitle className="flex items-center gap-2">
                            <StickyNote className="h-5 w-5 text-amber-500" />
                            New Note
                        </DialogTitle>
                        <DialogDescription>
                            Add a note about this contact
                        </DialogDescription>
                    </DialogHeader>

                    <div className="space-y-4">
                        {/* Templates */}
                        <div className="space-y-2">
                            <Label className="text-xs">Quick Templates</Label>
                            <div className="flex flex-wrap gap-1.5">
                                {noteTemplates.map((template) => (
                                    <Button
                                        key={template.label}
                                        type="button"
                                        variant="outline"
                                        size="sm"
                                        className="h-7 text-xs"
                                        onClick={() => applyTemplate(template.content)}
                                    >
                                        {template.label}
                                    </Button>
                                ))}
                            </div>
                        </div>

                        {/* Content */}
                        <div className="space-y-2">
                            <div className="flex items-center justify-between">
                                <Label htmlFor="note-content">Content</Label>
                                <span className="text-[10px] text-muted-foreground">
                                    {countWords(composeContent)} words · {composeContent.length} chars
                                </span>
                            </div>
                            <Textarea
                                ref={textareaRef}
                                id="note-content"
                                value={composeContent}
                                onChange={(e) => setComposeContent(e.target.value)}
                                placeholder="Write your note here..."
                                rows={8}
                                className="resize-none font-mono text-sm"
                            />
                        </div>

                        {/* Color Selection */}
                        {/* <div className="space-y-2">
              <Label className="text-xs">Color</Label>
              <div className="flex gap-2">
                {noteColors.map((color) => (
                  <button
                    key={color.id}
                    type="button"
                    className={cn(
                      "h-6 w-6 rounded-full border-2 transition-all",
                      color.class,
                      composeColor === color.id 
                        ? "ring-2 ring-primary ring-offset-2" 
                        : "hover:scale-110"
                    )}
                    onClick={() => setComposeColor(color.id)}
                    title={color.label}
                  />
                ))}
              </div>
            </div> */}
                    </div>

                    <DialogFooter className="gap-2 sm:gap-0">
                        <Button
                            variant="ghost"
                            onClick={() => {
                                setIsComposeOpen(false);
                                resetCompose();
                            }}
                        >
                            Cancel
                        </Button>
                        <Button
                            onClick={handleCreate}
                            disabled={isCreating || !composeContent.trim()}
                        >
                            {isCreating ? (
                                <Loader2 className="mr-2 h-4 w-4 animate-spin" />
                            ) : (
                                <Check className="mr-2 h-4 w-4" />
                            )}
                            Save Note
                        </Button>
                    </DialogFooter>
                </DialogContent>
            </Dialog>

            {/* Edit Note Dialog */}
            <Dialog open={!!editingNote} onOpenChange={(open) => !open && setEditingNote(null)}>
                <DialogContent className="sm:max-w-xl">
                    <DialogHeader>
                        <DialogTitle className="flex items-center gap-2">
                            <Edit3 className="h-5 w-5" />
                            Edit Note
                        </DialogTitle>
                        <DialogDescription>
                            Created {editingNote && formatNoteDate(editingNote.created_at)}
                        </DialogDescription>
                    </DialogHeader>

                    <div className="space-y-4">
                        <div className="space-y-2">
                            <div className="flex items-center justify-between">
                                <Label htmlFor="edit-content">Content</Label>
                                <span className="text-[10px] text-muted-foreground">
                                    {countWords(editContent)} words · {editContent.length} chars
                                </span>
                            </div>
                            <Textarea
                                id="edit-content"
                                value={editContent}
                                onChange={(e) => setEditContent(e.target.value)}
                                rows={8}
                                className="resize-none font-mono text-sm"
                                autoFocus
                            />
                        </div>
                    </div>

                    <DialogFooter className="gap-2 sm:gap-0">
                        <Button variant="ghost" onClick={() => setEditingNote(null)}>
                            Cancel
                        </Button>
                        <Button
                            onClick={handleUpdate}
                            disabled={isUpdating || !editContent.trim()}
                        >
                            {isUpdating ? (
                                <Loader2 className="mr-2 h-4 w-4 animate-spin" />
                            ) : (
                                <Check className="mr-2 h-4 w-4" />
                            )}
                            Save Changes
                        </Button>
                    </DialogFooter>
                </DialogContent>
            </Dialog>

            {/* Delete Confirmation */}
            <AlertDialog
                open={!!deletingNoteId}
                onOpenChange={(open) => !open && setDeletingNoteId(null)}
            >
                <AlertDialogContent>
                    <AlertDialogHeader>
                        <AlertDialogTitle>Delete Note</AlertDialogTitle>
                        <AlertDialogDescription>
                            Are you sure you want to delete this note? This action cannot be undone.
                        </AlertDialogDescription>
                    </AlertDialogHeader>
                    <AlertDialogFooter>
                        <AlertDialogCancel>Cancel</AlertDialogCancel>
                        <AlertDialogAction
                            onClick={handleDelete}
                            className="bg-destructive text-destructive-foreground hover:bg-destructive/90"
                        >
                            {isDeleting ? (
                                <>
                                    <Loader2 className="mr-2 h-4 w-4 animate-spin" />
                                    Deleting...
                                </>
                            ) : (
                                'Delete'
                            )}
                        </AlertDialogAction>
                    </AlertDialogFooter>
                </AlertDialogContent>
            </AlertDialog>
        </div>
    );
}