"use client";

import { useState } from "react";
import { Sparkles } from "lucide-react";
import { Button } from "@/components/ui/button";
import { useLocale } from "@/components/providers/locale-provider";
type AiMode =
  | "improve_wording"
  | "more_professional"
  | "shorter"
  | "warmer"
  | "formal_arabic"
  | "to_english"
  | "subject_lines"
  | "cta_text"
  | "personalize_category";

const MODES: { mode: AiMode; ar: string; en: string }[] = [
  { mode: "improve_wording", ar: "تحسين الصياغة", en: "Improve wording" },
  { mode: "more_professional", ar: "أكثر احترافية", en: "More professional" },
  { mode: "shorter", ar: "أقصر", en: "Shorter" },
  { mode: "warmer", ar: "أكثر دفئاً", en: "Warmer" },
  { mode: "formal_arabic", ar: "عربية رسمية", en: "Formal Arabic" },
  { mode: "to_english", ar: "تحويل للإنجليزية", en: "To English" },
  { mode: "subject_lines", ar: "عناوين مقترحة", en: "Subject lines" },
  { mode: "cta_text", ar: "نصوص CTA", en: "CTA suggestions" },
  { mode: "personalize_category", ar: "تخصيص حسب التصنيف", en: "Personalize category" },
];

export function AiAssistPanel({
  subject,
  content,
  category,
  language,
  onApplySubject,
  onApplyContent,
  onApplyCta,
}: {
  subject: string;
  content: string;
  category: string;
  language: string;
  onApplySubject: (s: string) => void;
  onApplyContent: (html: string) => void;
  onApplyCta: (text: string) => void;
}) {
  const { locale } = useLocale();
  const isAr = locale === "ar";
  const [loading, setLoading] = useState(false);
  const [available, setAvailable] = useState<boolean | null>(null);
  const [subjects, setSubjects] = useState<string[]>([]);
  const [improved, setImproved] = useState<string | undefined>();
  const [ctas, setCtas] = useState<string[]>([]);
  const [error, setError] = useState<string | null>(null);

  async function run(mode: AiMode) {
    setLoading(true);
    setError(null);
    const res = await fetch("/api/email-templates/ai-assist", {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({
        mode,
        subject,
        content,
        category,
        language,
        tone: "formal",
      }),
    });
    const json = await res.json();
    setLoading(false);
    if (!res.ok) {
      setError(json.error ?? "فشل");
      return;
    }
    setAvailable(json.available ?? false);
    setSubjects(json.subjectSuggestions ?? []);
    setImproved(json.improvedContent);
    setCtas(json.ctaSuggestions ?? []);
  }

  return (
    <div className="surface-elevated space-y-3 p-4">
      <div className="flex items-center gap-2">
        <Sparkles className="h-5 w-5 text-primary" />
        <h3 className="font-semibold">{isAr ? "تحسين بالذكاء" : "AI assist"}</h3>
      </div>
      {available === false ? (
        <p className="text-xs text-muted-foreground">
          {isAr
            ? "وضع الاقتراحات البسيطة — فعّل OpenAI للنتائج الأفضل"
            : "Simple suggestions mode — enable OpenAI for best results"}
        </p>
      ) : null}
      <div className="flex flex-wrap gap-1.5">
        {MODES.map((m) => (
          <Button
            key={m.mode}
            type="button"
            variant="outline"
            size="sm"
            disabled={loading}
            className="text-xs"
            onClick={() => void run(m.mode)}
          >
            {isAr ? m.ar : m.en}
          </Button>
        ))}
      </div>
      {loading ? (
        <p className="text-sm text-muted-foreground">{isAr ? "جاري..." : "Working..."}</p>
      ) : null}
      {error ? <p className="text-sm text-destructive">{error}</p> : null}
      {subjects.length > 0 ? (
        <div>
          <p className="mb-1 text-xs font-medium text-muted-foreground">
            {isAr ? "عناوين" : "Subjects"}
          </p>
          <ul className="space-y-1">
            {subjects.map((s) => (
              <li key={s}>
                <button
                  type="button"
                  className="w-full rounded-lg border border-border px-2 py-1.5 text-start text-xs hover:bg-primary/10"
                  onClick={() => onApplySubject(s)}
                >
                  {s}
                </button>
              </li>
            ))}
          </ul>
        </div>
      ) : null}
      {improved ? (
        <div>
          <p className="mb-1 text-xs font-medium text-muted-foreground">
            {isAr ? "محتوى محسّن" : "Improved content"}
          </p>
          <Button type="button" size="sm" onClick={() => onApplyContent(improved)}>
            {isAr ? "تطبيق" : "Apply"}
          </Button>
        </div>
      ) : null}
      {ctas.length > 0 ? (
        <div>
          <p className="mb-1 text-xs font-medium text-muted-foreground">CTA</p>
          <div className="flex flex-wrap gap-1">
            {ctas.map((c) => (
              <Button key={c} type="button" variant="outline" size="sm" onClick={() => onApplyCta(c)}>
                {c}
              </Button>
            ))}
          </div>
        </div>
      ) : null}
    </div>
  );
}
