"use client";

import { useState, useEffect } from "react";
import Link from "next/link";
import { Button } from "@/components/ui/button";
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card";
import { DEFAULT_THEME, themeValueToHex, hexToThemeValue } from "@/lib/theme";
import type { ThemeRecord } from "@/lib/theme";

const GROUPS: { title: string; keys: { key: string; label: string }[] }[] = [
  {
    title: "رنگ اصلی و دکمه‌ها",
    keys: [
      { key: "primary", label: "رنگ اصلی (Primary)" },
      { key: "primary-foreground", label: "متن روی اصلی" },
      { key: "ring", label: "حلقه فوکوس" },
    ],
  },
  {
    title: "پس‌زمینه و سطوح",
    keys: [
      { key: "background", label: "پس‌زمینه صفحه" },
      { key: "surface", label: "پس‌زمینه بخش‌ها" },
      { key: "card", label: "پس‌زمینه کارت" },
      { key: "card-foreground", label: "متن کارت" },
    ],
  },
  {
    title: "متن و عناصر کم‌رنگ",
    keys: [
      { key: "foreground", label: "متن اصلی" },
      { key: "muted", label: "پس‌زمینه کم‌رنگ" },
      { key: "muted-foreground", label: "متن کم‌رنگ" },
    ],
  },
  {
    title: "ثانویه و تاکید",
    keys: [
      { key: "secondary", label: "رنگ ثانویه" },
      { key: "secondary-foreground", label: "متن ثانویه" },
      { key: "accent", label: "رنگ تاکید (Accent)" },
      { key: "accent-foreground", label: "متن روی تاکید" },
    ],
  },
  {
    title: "حاشیه و ورودی",
    keys: [
      { key: "border", label: "حاشیه" },
      { key: "input", label: "ورودی فرم" },
    ],
  },
  {
    title: "پاپ‌اور و گرادیان",
    keys: [
      { key: "popover", label: "پاپ‌اور" },
      { key: "popover-foreground", label: "متن پاپ‌اور" },
      { key: "gradient-start", label: "شروع گرادیان" },
      { key: "gradient-end", label: "پایان گرادیان" },
    ],
  },
  {
    title: "خطا و تخریب",
    keys: [
      { key: "destructive", label: "رنگ خطا / حذف" },
      { key: "destructive-foreground", label: "متن روی خطا" },
    ],
  },
];

export function ThemeEditor() {
  const [theme, setTheme] = useState<ThemeRecord>({ ...DEFAULT_THEME });
  const [loading, setLoading] = useState(true);
  const [saving, setSaving] = useState(false);
  const [message, setMessage] = useState<{ type: "success" | "error"; text: string } | null>(null);

  useEffect(() => {
    fetch("/api/admin/theme")
      .then((r) => r.json())
      .then((data) => setTheme({ ...DEFAULT_THEME, ...data }))
      .catch(() => setTheme({ ...DEFAULT_THEME }))
      .finally(() => setLoading(false));
  }, []);

  const updateKey = (key: string, hex: string) => {
    setTheme((prev) => ({ ...prev, [key]: hexToThemeValue(hex) }));
  };

  const handleSave = async () => {
    setMessage(null);
    setSaving(true);
    try {
      const res = await fetch("/api/admin/theme", {
        method: "PUT",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify(theme),
      });
      if (res.ok) {
        setMessage({ type: "success", text: "تنظیمات ذخیره شد. صفحه سایت را رفرش کنید تا رنگ‌ها اعمال شوند." });
      } else {
        const data = await res.json().catch(() => ({}));
        setMessage({ type: "error", text: (data.error as string) || "خطا در ذخیره" });
      }
    } catch {
      setMessage({ type: "error", text: "خطا در ارتباط با سرور" });
    } finally {
      setSaving(false);
    }
  };

  const handleReset = () => {
    if (confirm("بازگردانی به رنگ‌های پیش‌فرض؟")) {
      setTheme({ ...DEFAULT_THEME });
      setMessage({ type: "success", text: "رنگ‌ها به پیش‌فرض بازگردانده شدند. ذخیره کنید تا اعمال شود." });
    }
  };

  if (loading) {
    return (
      <div className="text-muted-foreground py-8">در حال بارگذاری...</div>
    );
  }

  return (
    <div className="space-y-8">
      <div className="flex flex-wrap gap-3 items-center justify-between">
        <div>
          <h2 className="text-lg font-semibold">تنظیم رنگ‌ها</h2>
          <p className="text-sm text-muted-foreground mt-1">
            رنگ‌های سایت را تغییر دهید و ذخیره کنید. پس از ذخیره، صفحهٔ اصلی سایت را رفرش کنید.
          </p>
        </div>
        <div className="flex flex-wrap gap-2 items-center">
          <Button variant="outline" onClick={handleReset}>
            بازگردانی پیش‌فرض
          </Button>
          <Button onClick={handleSave} disabled={saving}>
            {saving ? "در حال ذخیره..." : "ذخیره تنظیمات"}
          </Button>
          <Button variant="outline" asChild>
            <Link href="/" target="_blank" rel="noopener noreferrer">
              مشاهده سایت
            </Link>
          </Button>
        </div>
      </div>

      {message && (
        <div
          className={`p-4 rounded-lg text-sm ${
            message.type === "success"
              ? "bg-green-500/10 text-green-700 dark:text-green-400"
              : "bg-destructive/10 text-destructive"
          }`}
          role="alert"
        >
          {message.text}
        </div>
      )}

      <div className="grid gap-6 md:grid-cols-2">
        {GROUPS.map((group) => (
          <Card key={group.title}>
            <CardHeader className="pb-3">
              <CardTitle className="text-base">{group.title}</CardTitle>
              <CardDescription>مقادیر HSL به‌صورت خودکار از رنگ انتخاب‌شده محاسبه می‌شوند.</CardDescription>
            </CardHeader>
            <CardContent className="space-y-4">
              {group.keys.map(({ key, label }) => (
                <div key={key} className="flex items-center gap-4">
                  <label className="flex-1 min-w-0 text-sm font-medium" htmlFor={`theme-${key}`}>
                    {label}
                  </label>
                  <div className="flex items-center gap-2">
                    <input
                      id={`theme-${key}`}
                      type="color"
                      value={themeValueToHex(theme[key] ?? DEFAULT_THEME[key] ?? "")}
                      onChange={(e) => updateKey(key, e.target.value)}
                      className="h-10 w-14 cursor-pointer rounded-lg border border-input bg-background"
                    />
                    <span className="text-xs text-muted-foreground font-mono w-20 truncate" title={theme[key]}>
                      {theme[key] || "—"}
                    </span>
                  </div>
                </div>
              ))}
            </CardContent>
          </Card>
        ))}
      </div>
    </div>
  );
}
