"use client";
import { WandSparkles } from "lucide-react";
import { Button } from "@/components/ui/button";
import { useState } from "react";
import { useAi } from "@/hooks/useAi";
import { EnhancedSettings } from "@/types";
import { toast } from "sonner";

export function PromptEnhancer({
  prompt,
  setPrompt,
  enhancedSettings,
}: {
  prompt: string;
  setPrompt: (p: string) => void;
  enhancedSettings: EnhancedSettings;
}) {
  const { model, provider, globalAiLoading } = useAi();
  const [loading, setLoading] = useState(false);

  const enhance = async () => {
    if (!prompt.trim()) return;
    try {
      setLoading(true);
      const res = await fetch('/api/enhance', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ prompt, model, provider, enhancedSettings }),
      });
      const data = await res.json();
      if (!res.ok || !data.ok) throw new Error(data.message || 'Failed to enhance prompt');
      setPrompt(data.prompt);
      toast.success('Prompt enhanced');
    } catch (e: any) {
      toast.error(e?.message || 'Failed to enhance');
    } finally {
      setLoading(false);
    }
  };

  return (
    <Button
      size="xs"
      variant="outline"
      className="!rounded-md"
      disabled={loading || globalAiLoading || !prompt.trim()}
      onClick={enhance}
    >
      <WandSparkles className="size-3.5" /> Improve
    </Button>
  );
}

