"use client";

import { useState, useEffect } from "react";
import { Loader2, Save } from "lucide-react";

interface Settings {
  siteTitle: string; description: string; currentStatus: string;
  telegramChannel: string; socialGithub: string; socialLinkedin: string;
  socialTwitter: string; socialTelegram: string; socialInstagram: string;
}

const empty: Settings = {
  siteTitle: "Ali Taghavi", description: "", currentStatus: "",
  telegramChannel: "", socialGithub: "", socialLinkedin: "",
  socialTwitter: "", socialTelegram: "", socialInstagram: "",
};

export default function AdminSettingsPage() {
  const [form, setForm] = useState<Settings>(empty);
  const [loading, setLoading] = useState(true);
  const [saving, setSaving] = useState(false);
  const [success, setSuccess] = useState(false);
  const [error, setError] = useState<string | null>(null);

  useEffect(() => {
    fetch("/api/admin/settings")
      .then((r) => r.json())
      .then((data) => {
        if (data && Object.keys(data).length > 0) setForm({ ...empty, ...data });
        setLoading(false);
      });
  }, []);

  function set(key: keyof Settings, value: string) {
    setForm((p) => ({ ...p, [key]: value }));
  }

  async function handleSave(e: React.FormEvent) {
    e.preventDefault();
    setError(null); setSaving(true);
    try {
      const res = await fetch("/api/admin/settings", {
        method: "PUT", headers: { "Content-Type": "application/json" },
        body: JSON.stringify(form),
      });
      if (!res.ok) throw new Error((await res.json()).error ?? "Save failed");
      setSuccess(true);
      setTimeout(() => setSuccess(false), 2000);
    } catch (e) { setError(e instanceof Error ? e.message : "خطا"); }
    finally { setSaving(false); }
  }

  if (loading) return <div className="flex justify-center py-20"><Loader2 className="animate-spin text-text-secondary" /></div>;

  return (
    <div>
      <h1 className="mb-6 text-2xl font-bold text-text-primary">تنظیمات سایت</h1>
      <form onSubmit={handleSave} className="space-y-8 max-w-2xl">
        {error && <div className="rounded-lg border border-danger/30 bg-danger/10 px-4 py-3 text-sm text-danger">{error}</div>}
        {success && <div className="rounded-lg border border-success/30 bg-success/10 px-4 py-3 text-sm text-success">تنظیمات ذخیره شد ✓</div>}

        <div className="rounded-xl border border-border bg-surface p-6 space-y-4">
          <h2 className="font-semibold text-text-primary border-b border-border pb-3">اطلاعات سایت</h2>
          <div>
            <label className="block text-sm font-medium text-text-primary mb-1.5">نام سایت</label>
            <input type="text" value={form.siteTitle} onChange={(e) => set("siteTitle", e.target.value)} className="admin-input w-full" />
          </div>
          <div>
            <label className="block text-sm font-medium text-text-primary mb-1.5">توضیحات</label>
            <textarea value={form.description} onChange={(e) => set("description", e.target.value)} rows={3} className="admin-input w-full resize-none" />
          </div>
          <div>
            <label className="block text-sm font-medium text-text-primary mb-1.5">وضعیت فعلی (در صفحه About نمایش داده می‌شود)</label>
            <textarea value={form.currentStatus} onChange={(e) => set("currentStatus", e.target.value)} rows={2} className="admin-input w-full resize-none" placeholder="مثلاً: در حال ساخت HyperAccount..." />
          </div>
        </div>

        <div className="rounded-xl border border-border bg-surface p-6 space-y-4">
          <h2 className="font-semibold text-text-primary border-b border-border pb-3">شبکه‌های اجتماعی</h2>
          <div className="grid gap-4 sm:grid-cols-2">
            {[
              { key: "socialGithub", label: "GitHub", placeholder: "https://github.com/..." },
              { key: "socialLinkedin", label: "LinkedIn", placeholder: "https://linkedin.com/in/..." },
              { key: "socialTwitter", label: "Twitter/X", placeholder: "https://twitter.com/..." },
              { key: "socialTelegram", label: "Telegram", placeholder: "https://t.me/..." },
              { key: "socialInstagram", label: "Instagram", placeholder: "https://instagram.com/..." },
              { key: "telegramChannel", label: "کانال تلگرام", placeholder: "https://t.me/channel..." },
            ].map((field) => (
              <div key={field.key}>
                <label className="block text-sm font-medium text-text-primary mb-1.5">{field.label}</label>
                <input
                  type="url"
                  value={form[field.key as keyof Settings]}
                  onChange={(e) => set(field.key as keyof Settings, e.target.value)}
                  dir="ltr"
                  className="admin-input w-full"
                  placeholder={field.placeholder}
                />
              </div>
            ))}
          </div>
        </div>

        <div className="flex justify-end">
          <button type="submit" disabled={saving} className="flex items-center gap-2 rounded-lg bg-accent px-5 py-2 text-sm font-semibold text-background hover:bg-accent-hover disabled:opacity-60 transition-colors">
            {saving ? <Loader2 size={14} className="animate-spin" /> : <Save size={14} />}
            ذخیره تنظیمات
          </button>
        </div>
      </form>
    </div>
  );
}
