"use client";

import { useState } from "react";
import { Loader2, Sparkles } from "lucide-react";
import { Button } from "@/components/ui/button";
import { useLocale } from "@/components/providers/locale-provider";

export function AiSegmentBuilderPanel({
  onApply,
}: {
  onApply: (data: {
    filters: Record<string, unknown>;
    targetType: string;
    targetChannel: string;
  }) => void;
}) {
  const { locale } = useLocale();
  const isAr = locale === "ar";
  const [query, setQuery] = useState("");
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState<string | null>(null);
  const [preview, setPreview] = useState<{
    filters: Record<string, unknown>;
    targetType: string;
    targetChannel: string;
    explanation: string;
  } | null>(null);

  async function build() {
    if (!query.trim()) return;
    setLoading(true);
    setError(null);
    const res = await fetch("/api/ai/segment-builder", {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({ query: query.trim() }),
    });
    const json = await res.json();
    setLoading(false);
    if (!res.ok) {
      setError(json.error ?? "فشل");
      return;
    }
    setPreview(json);
  }

  return (
    <div className="space-y-3 rounded-lg border border-dashed border-primary/30 p-4">
      <h3 className="flex items-center gap-2 font-semibold">
        <Sparkles className="h-4 w-4" />
        {isAr ? "ابنِ الشريحة بالذكاء الاصطناعي" : "AI segment builder"}
      </h3>
      <textarea
        className="min-h-[80px] w-full rounded-md border px-2 py-1 text-sm"
        placeholder={
          isAr
            ? "مثال: شركات تقنية بالرياض لديها بريد صالح"
            : "e.g. tech companies in Riyadh with valid email"
        }
        value={query}
        onChange={(e) => setQuery(e.target.value)}
      />
      <Button type="button" disabled={loading} onClick={() => void build()}>
        {loading ? <Loader2 className="h-4 w-4 animate-spin" /> : null}
        {isAr ? "تحليل" : "Analyze"}
      </Button>
      {error ? <p className="text-sm text-destructive">{error}</p> : null}
      {preview ? (
        <div className="space-y-2 rounded border bg-muted/20 p-3 text-sm">
          <p>{preview.explanation}</p>
          <pre className="overflow-x-auto rounded bg-background p-2 text-xs">
            {JSON.stringify(preview.filters, null, 2)}
          </pre>
          <p className="text-xs text-muted-foreground">
            {isAr ? "لن يتم الحفظ تلقائياً — راجع ثم طبّق." : "Not saved automatically."}
          </p>
          <Button
            type="button"
            size="sm"
            onClick={() =>
              onApply({
                filters: preview.filters,
                targetType: preview.targetType,
                targetChannel: preview.targetChannel,
              })
            }
          >
            {isAr ? "تطبيق الفلاتر" : "Apply filters"}
          </Button>
        </div>
      ) : null}
    </div>
  );
}
