"use client";

import { useState } from "react";
import { useRouter } from "next/navigation";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import type { HomeFortunesSettings } from "@/lib/home-fortunes";

export function HomeFortunesEditor({ initial }: { initial: HomeFortunesSettings }) {
  const router = useRouter();
  const [sectionTitle, setSectionTitle] = useState(initial.sectionTitle);
  const [sectionSubtitle, setSectionSubtitle] = useState(initial.sectionSubtitle);
  const [saving, setSaving] = useState(false);
  const [error, setError] = useState<string | null>(null);
  const [success, setSuccess] = useState<string | null>(null);

  async function onSave() {
    setSaving(true);
    setError(null);
    setSuccess(null);
    const payload = {
      sectionTitle: sectionTitle.trim(),
      sectionSubtitle: sectionSubtitle.trim(),
    };
    if (!payload.sectionTitle || !payload.sectionSubtitle) {
      setSaving(false);
      setError("عنوان و توضیح بخش را وارد کنید.");
      return;
    }
    try {
      const res = await fetch("/api/admin/home-fortunes", {
        method: "PUT",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify(payload),
      });
      if (!res.ok) {
        const data = await res.json().catch(() => ({}));
        throw new Error((data?.error as string) ?? "خطا در ذخیره");
      }
      setSuccess("متن بخش فال در صفحه اصلی ذخیره شد.");
      router.refresh();
    } catch (e) {
      setError(e instanceof Error ? e.message : "خطا در ذخیره");
    } finally {
      setSaving(false);
    }
  }

  return (
    <Card className="mb-8 max-w-xl">
      <CardHeader>
        <CardTitle className="text-base">نمایش در صفحه اصلی</CardTitle>
      </CardHeader>
      <CardContent className="space-y-4">
        {error && (
          <p className="text-sm text-destructive bg-destructive/10 p-3 rounded-md" role="alert">
            {error}
          </p>
        )}
        {success && (
          <p className="text-sm text-green-700 bg-green-50 dark:bg-green-950/30 p-3 rounded-md">
            {success}
          </p>
        )}
        <div>
          <Label>عنوان بخش</Label>
          <Input
            value={sectionTitle}
            onChange={(e) => setSectionTitle(e.target.value)}
            className="mt-1"
          />
        </div>
        <div>
          <Label>توضیح زیر عنوان</Label>
          <Input
            value={sectionSubtitle}
            onChange={(e) => setSectionSubtitle(e.target.value)}
            className="mt-1"
          />
          <p className="text-xs text-muted-foreground mt-1">
            مثلاً: راهنمایی روزانه و پیش‌بینی ماهانه تاروت
          </p>
        </div>
        <Button type="button" onClick={onSave} disabled={saving}>
          {saving ? "در حال ذخیره..." : "ذخیره متن صفحه اصلی"}
        </Button>
      </CardContent>
    </Card>
  );
}
