"use client";

import { FormEvent, useState } from "react";
import { Banner, Button, TextareaField } from "@/components/admin/controls";
import { simulateRecommendations } from "../adapters/admin";

/** Recommendation rule simulator — no AI; rule engine API only. */
export function AdminRecommendationSimulator() {
  const [body, setBody] = useState(
    JSON.stringify({ answers: { business_type_code: "" }, version: "recommendation.v1" }, null, 2)
  );
  const [out, setOut] = useState("");
  const [error, setError] = useState("");
  const [busy, setBusy] = useState(false);

  const run = async (e: FormEvent) => {
    e.preventDefault();
    setBusy(true);
    setError("");
    setOut("");
    try {
      const parsed = JSON.parse(body) as { answers?: Record<string, unknown> };
      const res = await simulateRecommendations(parsed.answers || parsed);
      if (!res.ok) {
        setError(res.message);
        return;
      }
      setOut(JSON.stringify(res.data, null, 2));
    } catch {
      setError("JSON نامعتبر");
    } finally {
      setBusy(false);
    }
  };

  return (
    <section className="rounded-2xl border border-gray-100 bg-white p-5 shadow-sm">
      <h3 className="text-base font-bold text-secondary">شبیه‌ساز پیشنهاد</h3>
      <p className="mt-1 text-xs text-gray-500">
        POST /api/v1/commercial/recommendations — بدون مدل AI.
      </p>
      {error ? <div className="mt-3"><Banner variant="error">{error}</Banner></div> : null}
      <form onSubmit={(e) => void run(e)} className="mt-4 space-y-3">
        <TextareaField label="Request JSON" value={body} onValue={setBody} rows={8} dir="ltr" className="font-mono text-xs" />
        <Button type="submit" loading={busy}>
          اجرا
        </Button>
      </form>
      {out ? (
        <pre className="mt-4 max-h-80 overflow-auto rounded-xl bg-gray-50 p-3 font-mono text-[11px]" dir="ltr">
          {out}
        </pre>
      ) : null}
    </section>
  );
}
