"use client";

import { useState, useTransition } from "react";
import { updateSiteSetting } from "@/lib/content-actions";

export default function SettingsEditor({
  settingKey,
  title,
  value,
}: {
  settingKey: string;
  title: string;
  value: unknown;
}) {
  const [text, setText] = useState(JSON.stringify(value, null, 2));
  const [isPending, startTransition] = useTransition();
  const [message, setMessage] = useState<string | null>(null);

  function handleSave() {
    setMessage(null);
    let parsed: unknown;
    try {
      parsed = JSON.parse(text);
    } catch {
      setMessage("صيغة JSON غير صحيحة");
      return;
    }
    startTransition(async () => {
      const result = await updateSiteSetting(settingKey, parsed);
      setMessage(result.ok ? "تم الحفظ ✓" : result.error || "تعذّر الحفظ");
    });
  }

  return (
    <div className="rounded-2xl border border-black/10 bg-white p-6">
      <h3 className="mb-3 font-bold text-[#1A1A1A]">{title}</h3>
      <textarea
        value={text}
        onChange={(e) => setText(e.target.value)}
        rows={10}
        dir="ltr"
        className="w-full resize-y rounded-lg border border-black/10 bg-[#F5F3EF] px-4 py-3 font-mono text-xs outline-none focus:border-[#C9A24A]"
      />
      <div className="mt-3 flex items-center gap-3">
        <button
          onClick={handleSave}
          disabled={isPending}
          className="rounded-lg bg-[#1A1A1A] px-4 py-2 text-sm font-semibold text-white transition hover:bg-black disabled:opacity-60"
        >
          {isPending ? "جارِ الحفظ..." : "حفظ"}
        </button>
        {message && (
          <span className={`text-xs ${message.includes("✓") ? "text-emerald-600" : "text-red-500"}`}>
            {message}
          </span>
        )}
      </div>
    </div>
  );
}
