"use client";

import { useState } from "react";
import { Plus, Trash2, Edit2, X, Sparkles } from "lucide-react";
import { useSettingsStore, AIPrompt } from "@/lib/settings-store";
import { useConfirm } from "@/components/confirm-provider";

export function PromptManagement() {
    const confirm = useConfirm();
    const { prompts, addPrompt, updatePrompt, deletePrompt, resetPrompts } = useSettingsStore();
    const [editing, setEditing] = useState<AIPrompt | null>(null);
    const [isNew, setIsNew] = useState(false);

    const handleSave = (e: React.FormEvent) => {
        e.preventDefault();
        if (!editing) return;

        const label = editing.label.trim();
        const id = editing.id.trim();
        const systemPrompt = editing.systemPrompt.trim();
        if (!label || !id || !systemPrompt) return;

        const payload = { ...editing, label, id, systemPrompt };
        if (isNew) {
            addPrompt(payload);
        } else {
            updatePrompt(payload.id, payload);
        }
        setEditing(null);
        setIsNew(false);
    };

    const startNew = () => {
        setEditing({
            id: `custom_${Date.now()}`,
            label: "新功能",
            description: "功能描述...",
            systemPrompt: "你是一个专业助手，请根据用户输入完成任务。",
        });
        setIsNew(true);
    };

    return (
        <section className="space-y-5">
            <div className="flex items-center justify-between gap-2 border-b border-border/70 pb-3">
                <div className="flex items-center gap-2">
                    <Sparkles size={20} className="text-primary" />
                    <h2 className="text-xl font-semibold">自定义 AI 提示词</h2>
                </div>
                <div className="flex items-center gap-2">
                    <button onClick={startNew} className="ui-btn-primary px-3 py-1.5 text-xs">
                        <Plus size={14} />
                        添加提示词
                    </button>
                    <button onClick={resetPrompts} className="ui-btn-secondary px-3 py-1.5 text-xs">
                        恢复默认
                    </button>
                </div>
            </div>

            <div className="grid gap-3 md:grid-cols-2">
                {prompts.map((prompt) => (
                    <div key={prompt.id} className="rounded-xl border border-border/70 bg-muted/25 p-3">
                        <div className="flex items-start justify-between gap-2">
                            <div>
                                <h3 className="flex items-center gap-2 text-sm font-medium">
                                    {prompt.label}
                                    <span className="rounded bg-muted px-1.5 py-0.5 font-mono text-[10px] text-muted-foreground">
                                        {prompt.id}
                                    </span>
                                </h3>
                                <p className="mt-1 line-clamp-1 text-xs text-muted-foreground">{prompt.description}</p>
                            </div>
                            <div className="flex items-center gap-1">
                                <button
                                    onClick={() => {
                                        setEditing(prompt);
                                        setIsNew(false);
                                    }}
                                    className="ui-icon-btn h-8 w-8"
                                    title="编辑"
                                >
                                    <Edit2 size={14} />
                                </button>
                                <button
                                    onClick={async () => {
                                        const ok = await confirm({
                                            title: "删除提示词",
                                            description: `确认删除“${prompt.label}”吗？`,
                                            confirmText: "删除",
                                            cancelText: "取消",
                                            tone: "danger",
                                        });
                                        if (ok) deletePrompt(prompt.id);
                                    }}
                                    className="ui-icon-btn h-8 w-8 hover:text-destructive"
                                    title="删除"
                                >
                                    <Trash2 size={14} />
                                </button>
                            </div>
                        </div>
                    </div>
                ))}
            </div>

            {editing && (
                <div className="fixed inset-0 z-50 flex items-center justify-center bg-black/40 p-4 backdrop-blur-sm">
                    <div className="ui-card w-full max-w-xl p-6 shadow-2xl animate-in zoom-in-95 duration-200">
                        <div className="flex items-center justify-between border-b border-border/60 pb-3">
                            <h3 className="text-lg font-semibold">{isNew ? "新建 AI 提示词" : "编辑 AI 提示词"}</h3>
                            <button onClick={() => setEditing(null)} className="ui-icon-btn h-8 w-8">
                                <X size={18} />
                            </button>
                        </div>

                        <form onSubmit={handleSave} className="mt-4 space-y-4">
                            <div className="grid grid-cols-2 gap-4">
                                <label className="space-y-2 text-sm">
                                    <span className="font-medium">名称</span>
                                    <input
                                        type="text"
                                        value={editing.label}
                                        onChange={(e) => setEditing({ ...editing, label: e.target.value })}
                                        className="ui-input"
                                        required
                                    />
                                </label>
                                <label className="space-y-2 text-sm">
                                    <span className="font-medium">唯一标识</span>
                                    <input
                                        type="text"
                                        value={editing.id}
                                        onChange={(e) => setEditing({ ...editing, id: e.target.value })}
                                        className="ui-input"
                                        readOnly={!isNew}
                                        required
                                    />
                                </label>
                            </div>

                            <label className="space-y-2 text-sm block">
                                <span className="font-medium">简短描述</span>
                                <input
                                    type="text"
                                    value={editing.description}
                                    onChange={(e) => setEditing({ ...editing, description: e.target.value })}
                                    className="ui-input"
                                />
                            </label>

                            <label className="space-y-2 text-sm block">
                                <span className="font-medium">系统提示词</span>
                                <textarea
                                    value={editing.systemPrompt}
                                    onChange={(e) => setEditing({ ...editing, systemPrompt: e.target.value })}
                                    className="ui-input min-h-32 font-mono"
                                    required
                                />
                                <p className="text-xs text-muted-foreground">这段内容会发送给模型，用于定义角色和回答风格。</p>
                            </label>

                            <div className="flex justify-end gap-2 pt-1">
                                <button type="button" onClick={() => setEditing(null)} className="ui-btn-secondary">
                                    取消
                                </button>
                                <button type="submit" className="ui-btn-primary">
                                    保存
                                </button>
                            </div>
                        </form>
                    </div>
                </div>
            )}
        </section>
    );
}
