import React, { useEffect, useState } from 'react';
import { SideSheet } from './ui/SideSheet';
import { SavedMessage, getBookmarks, deleteBookmark } from '../services/bookmarks';
import { Trash2, AlertCircle, BookmarkX, Loader2 } from 'lucide-react';
import ReactMarkdown from 'react-markdown';
import remarkGfm from 'remark-gfm';

interface SavedMessagesSheetProps {
    isOpen: boolean;
    onClose: () => void;
    onUnbookmark?: (id: string) => void;
}

const SavedMessagesSheet: React.FC<SavedMessagesSheetProps> = ({ isOpen, onClose, onUnbookmark }) => {
    const [bookmarks, setBookmarks] = useState<SavedMessage[]>([]);
    const [loading, setLoading] = useState(false);
    const [error, setError] = useState<string | null>(null);

    const fetchBookmarks = async () => {
        setLoading(true);
        setError(null);
        try {
            const data = await getBookmarks();
            setBookmarks(data);
        } catch (err: any) {
            if (err.message !== 'Unauthorized') {
                console.warn("Failed to fetch bookmarks:", err);
            }
            // Fallback to empty if API fails
            setBookmarks([]);
        } finally {
            setLoading(false);
        }
    };

    useEffect(() => {
        if (isOpen) {
            fetchBookmarks();
        }
    }, [isOpen]);

    const handleDelete = async (id: string, e: React.MouseEvent) => {
        e.stopPropagation();
        try {
            const success = await deleteBookmark(id);
            if (success) {
                setBookmarks(prev => prev.filter(b => b.id !== id));
                if (onUnbookmark) {
                    onUnbookmark(id);
                }
            } else {
                // Optimistic update fallback
                setBookmarks(prev => prev.filter(b => b.id !== id));
                if (onUnbookmark) {
                    onUnbookmark(id);
                }
            }
        } catch (error) {
            console.error("Delete failed", error);
        }
    };

    return (
        <SideSheet
            isOpen={isOpen}
            onClose={onClose}
            title="Saved Messages"
            width="md"
        >
            <div className="flex flex-col h-full">
                {loading ? (
                    <div className="flex flex-col items-center justify-center p-8 text-on-surface-variant">
                        <Loader2 size={32} className="animate-spin mb-2" />
                        <p>Loading...</p>
                    </div>
                ) : error ? (
                    <div className="flex flex-col items-center justify-center p-8 text-error">
                        <AlertCircle size={32} className="mb-2" />
                        <p>{error}</p>
                    </div>
                ) : bookmarks.length === 0 ? (
                    <div className="flex flex-col items-center justify-center h-full text-on-surface-variant opacity-60">
                        <BookmarkX size={48} className="mb-4" />
                        <p>No saved messages yet.</p>
                    </div>
                ) : (
                    <div className="space-y-4 p-1">
                        {bookmarks.map((msg) => (
                            <div key={msg.id} className="bg-surface-container-high rounded-xl p-4 shadow-sm border border-outline-variant/20 relative group">
                                <div className="pr-8 prose prose-invert prose-sm max-w-none text-on-surface">
                                    <ReactMarkdown remarkPlugins={[remarkGfm]}>
                                        {msg.content}
                                    </ReactMarkdown>
                                </div>
                                <div className="text-xs text-on-surface-variant mt-3 pt-3 border-t border-outline-variant/10 flex justify-between items-center">
                                    <span>{new Date(msg.createdAt).toLocaleDateString()}</span>
                                    <button
                                        onClick={(e) => handleDelete(msg.id, e)}
                                        className="p-2 text-on-surface-variant hover:text-error hover:bg-error/10 rounded-full transition-colors absolute top-2 right-2 opacity-100 sm:opacity-0 sm:group-hover:opacity-100"
                                        title="Remove bookmark"
                                    >
                                        <Trash2 size={16} />
                                    </button>
                                </div>
                            </div>
                        ))}
                    </div>
                )}
            </div>
        </SideSheet>
    );
};

export default SavedMessagesSheet;
