"use client";

import React from "react";
import { Sparkles, Wand2 } from "lucide-react";
import { createPortal } from "react-dom";
import { useSettingsStore, AIPrompt } from "@/lib/settings-store";

interface AIAssistProps {
    onSuggest: (prompt: AIPrompt) => void;
    isOpen: boolean;
    onClose: () => void;
}

export function AIAssist({ onSuggest, isOpen, onClose }: AIAssistProps) {
    const { prompts } = useSettingsStore();

    if (!isOpen) return null;
    if (typeof document === "undefined") return null;

    return createPortal(
        <div className="fixed inset-0 z-[9999] flex items-center justify-center bg-black/25 p-3 backdrop-blur-[2px]" onClick={onClose}>
            <div className="ui-card w-full max-w-[320px] overflow-hidden" onClick={(e) => e.stopPropagation()}>
                <div className="flex items-center gap-2 border-b border-border/60 bg-muted/40 px-4 py-3 text-sm font-medium text-muted-foreground">
                    <Sparkles size={16} className="text-primary" />
                    AI 写作助手
                </div>
                <div className="max-h-[55vh] space-y-1 overflow-y-auto p-2 sm:max-h-[320px]">
                    {prompts.map((prompt) => (
                        <button
                            key={prompt.id}
                            onClick={() => onSuggest(prompt)}
                            className="w-full rounded-lg p-2.5 text-left transition-colors hover:bg-muted/70"
                        >
                            <div className="flex items-start gap-3">
                                <div className="mt-0.5 rounded-md bg-primary/10 p-1.5">
                                    <Wand2 size={16} className="text-primary" />
                                </div>
                                <div>
                                    <div className="text-sm font-medium text-foreground">{prompt.label}</div>
                                    <div className="text-[11px] text-muted-foreground">{prompt.description}</div>
                                </div>
                            </div>
                        </button>
                    ))}
                </div>
                <div className="border-t border-border/60 bg-muted/20 px-3 py-2 text-[10px] text-muted-foreground">
                    <div className="flex items-center justify-between">
                        <span>AI Powered</span>
                        <span className="opacity-70">按 ESC 关闭</span>
                    </div>
                </div>
            </div>
        </div>,
        document.body
    );
}
