"use client";

import { useState } from "react";
import { Loader2, MessageSquare } from "lucide-react";
import { Button } from "@/components/ui/button";
import { useLocale } from "@/components/providers/locale-provider";

export function AiFollowUpPanel({
  lastReply,
  conversationHistory,
  companyContext,
  leadContext,
  subject,
  onApply,
}: {
  lastReply?: string;
  conversationHistory?: string;
  companyContext?: string;
  leadContext?: string;
  subject?: string;
  onApply: (reply: string) => void;
}) {
  const { locale } = useLocale();
  const isAr = locale === "ar";
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState<string | null>(null);
  const [suggested, setSuggested] = useState<string | null>(null);

  async function generate() {
    setLoading(true);
    setError(null);
    const res = await fetch("/api/ai/follow-up", {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({
        lastReply,
        conversationHistory,
        companyContext,
        leadContext,
        subject,
      }),
    });
    const json = await res.json();
    setLoading(false);
    if (!res.ok) {
      setError(json.error ?? "فشل");
      return;
    }
    if (json.error) setError(json.error);
    setSuggested(json.suggestedReply ?? "");
  }

  return (
    <div className="space-y-2 rounded-lg border border-border p-3">
      <h3 className="flex items-center gap-2 text-sm font-semibold">
        <MessageSquare className="h-4 w-4" />
        {isAr ? "إنشاء رد مقترح" : "Suggested reply"}
      </h3>
      <Button type="button" size="sm" variant="outline" disabled={loading} onClick={() => void generate()}>
        {loading ? <Loader2 className="h-3 w-3 animate-spin" /> : null}
        {isAr ? "توليد" : "Generate"}
      </Button>
      {error ? <p className="text-sm text-amber-700">{error}</p> : null}
      {suggested ? (
        <div className="space-y-2 text-sm">
          <div className="prose prose-sm max-w-none rounded bg-muted/30 p-2" dangerouslySetInnerHTML={{ __html: suggested }} />
          <Button type="button" size="sm" onClick={() => onApply(suggested)}>
            {isAr ? "استخدام في الرد" : "Use in reply"}
          </Button>
        </div>
      ) : null}
    </div>
  );
}
