"use client";

import Image from "next/image";
import { useCallback, useEffect, useState } from "react";
import { useBrand } from "@/components/providers/brand-provider";
import { buildEmailFooterHtml } from "@/lib/email-footer";
import { getLogoForTheme, type BrandSettings } from "@/lib/brand-settings";
import { PageLayout } from "@/components/design-system/page-layout";

type FormState = BrandSettings;

const FIELDS: Array<{
  key: keyof FormState;
  labelAr: string;
  labelEn: string;
  type?: string;
}> = [
  { key: "platformName", labelAr: "اسم المنصة", labelEn: "Platform name" },
  { key: "companyName", labelAr: "اسم الشركة", labelEn: "Company name" },
  { key: "primaryColor", labelAr: "اللون الأساسي", labelEn: "Primary color", type: "color" },
  { key: "secondaryColor", labelAr: "اللون الثانوي", labelEn: "Secondary color", type: "color" },
  { key: "website", labelAr: "الموقع الإلكتروني", labelEn: "Website" },
  { key: "supportEmail", labelAr: "بريد الدعم", labelEn: "Support email" },
  { key: "supportPhone", labelAr: "هاتف الدعم", labelEn: "Support phone" },
  { key: "address", labelAr: "العنوان", labelEn: "Address" },
];

const UPLOADS = [
  { assetType: "logoLight" as const, labelAr: "شعار (فاتح)", labelEn: "Logo (light)" },
  { assetType: "logoDark" as const, labelAr: "شعار (داكن)", labelEn: "Logo (dark)" },
  { assetType: "favicon" as const, labelAr: "أيقونة المتصفح", labelEn: "Favicon" },
];

export function BrandingSettingsClient() {
  const { refresh: refreshBrand, applyBrand } = useBrand();
  const [form, setForm] = useState<FormState | null>(null);
  const [loading, setLoading] = useState(true);
  const [message, setMessage] = useState("");
  const [error, setError] = useState("");
  const [uploading, setUploading] = useState<string | null>(null);

  const load = useCallback(async () => {
    setLoading(true);
    const res = await fetch("/api/settings/branding", { cache: "no-store" });
    const json = (await res.json()) as { data?: FormState; error?: string };
    if (!res.ok) {
      setError(json.error ?? "Failed to load");
    } else {
      setForm(json.data ?? null);
    }
    setLoading(false);
  }, []);

  useEffect(() => {
    const timeout = window.setTimeout(() => {
      void load();
    }, 0);
    return () => window.clearTimeout(timeout);
  }, [load]);

  async function save(e: React.FormEvent) {
    e.preventDefault();
    if (!form) return;
    setError("");
    setMessage("");
    const res = await fetch("/api/settings/branding", {
      method: "PATCH",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify(form),
    });
    const json = (await res.json()) as { error?: string };
    if (!res.ok) {
      setError(json.error ?? "Save failed");
      return;
    }
    setMessage("تم حفظ إعدادات العلامة التجارية");
    await load();
    await refreshBrand();
  }

  async function uploadAsset(assetType: (typeof UPLOADS)[number]["assetType"], file: File) {
    setUploading(assetType);
    setError("");
    const formData = new FormData();
    formData.append("assetType", assetType);
    formData.append("file", file);
    const res = await fetch("/api/settings/branding/upload", {
      method: "POST",
      body: formData,
    });
    const json = (await res.json()) as { data?: { brand: FormState }; error?: string };
    setUploading(null);
    if (!res.ok) {
      setError(json.error ?? "Upload failed");
      return;
    }
    if (json.data?.brand) {
      setForm(json.data.brand);
      applyBrand(json.data.brand);
    }
    setMessage("تم رفع الملف");
    await load();
    await refreshBrand();
  }

  if (loading || !form) {
    return <p className="text-sm text-muted-foreground">جاري التحميل...</p>;
  }

  const logoLight = getLogoForTheme(form, "light");
  const emailFooter = buildEmailFooterHtml(form, "rtl");

  return (
    <PageLayout
      title="العلامة التجارية"
      description="Brand Settings — white-label platform identity"
      maxWidth={false}
    >
      {error ? <p className="mb-4 text-sm text-red-600">{error}</p> : null}
      {message ? <p className="mb-4 text-sm text-green-700">{message}</p> : null}

      <div className="grid gap-6 xl:grid-cols-[1fr_360px]">
        <form onSubmit={(e) => void save(e)} className="space-y-6">
          <section className="surface-elevated space-y-4 p-5">
            <h2 className="font-semibold">Brand Settings</h2>
            <div className="grid gap-3 sm:grid-cols-2">
              {FIELDS.map((field) => (
                <label key={field.key} className="block text-sm">
                  <span className="font-medium">{field.labelAr}</span>
                  <span className="ms-1 text-xs text-muted-foreground">({field.labelEn})</span>
                  <input
                    className="mt-1 w-full rounded border px-3 py-2"
                    type={field.type ?? "text"}
                    value={form[field.key] ?? ""}
                    onChange={(e) => setForm({ ...form, [field.key]: e.target.value })}
                  />
                </label>
              ))}
            </div>
          </section>

          <section className="surface-elevated space-y-4 p-5">
            <h2 className="font-semibold">الشعارات والأيقونات</h2>
            <div className="grid gap-4 sm:grid-cols-3">
              {UPLOADS.map((item) => (
                <label key={item.assetType} className="block rounded border p-3 text-sm">
                  <span className="font-medium">{item.labelAr}</span>
                  <span className="block text-xs text-muted-foreground">{item.labelEn}</span>
                  {form[item.assetType] ? (
                    <p className="mt-2 truncate text-xs text-muted-foreground">
                      {form[item.assetType]}
                    </p>
                  ) : null}
                  <input
                    type="file"
                    accept="image/png,image/jpeg,image/webp,image/svg+xml,image/x-icon"
                    className="mt-2 w-full text-xs"
                    disabled={uploading === item.assetType}
                    onChange={(e) => {
                      const file = e.target.files?.[0];
                      if (file) void uploadAsset(item.assetType, file);
                    }}
                  />
                </label>
              ))}
            </div>
          </section>

          <button
            type="submit"
            className="rounded bg-primary px-4 py-2 text-sm text-primary-foreground"
          >
            حفظ الإعدادات
          </button>
        </form>

        <div className="space-y-4">
          <PreviewCard title="Sidebar" titleAr="الشريط الجانبي">
            <div className="rounded-lg border bg-card p-3">
              {logoLight ? (
                <Image
                  src={logoLight}
                  alt={form.platformName}
                  width={140}
                  height={40}
                  className="h-10 w-auto object-contain"
                  unoptimized
                />
              ) : (
                <p className="text-sm font-bold">{form.platformName}</p>
              )}
              <p className="mt-1 text-xs text-muted-foreground">{form.companyName}</p>
            </div>
          </PreviewCard>

          <PreviewCard title="Login" titleAr="تسجيل الدخول">
            <div className="rounded-lg border bg-card p-4 text-center">
              {logoLight ? (
                <div className="mx-auto mb-2 flex h-12 w-12 items-center justify-center">
                  <Image
                    src={logoLight}
                    alt={form.platformName}
                    width={40}
                    height={40}
                    className="object-contain"
                    unoptimized
                  />
                </div>
              ) : (
                <p className="mb-2 text-lg font-bold">{form.platformName}</p>
              )}
              <p className="font-semibold">{form.platformName}</p>
              <p className="text-xs text-muted-foreground">{form.companyName}</p>
            </div>
          </PreviewCard>

          <PreviewCard title="Email Header" titleAr="رأس البريد">
            <div
              className="rounded-lg p-4 text-center text-white"
              style={{ backgroundColor: form.primaryColor }}
            >
              {logoLight ? (
                <Image
                  src={logoLight}
                  alt={form.platformName}
                  width={120}
                  height={32}
                  className="mx-auto h-8 object-contain"
                  unoptimized
                />
              ) : (
                <p className="font-semibold">{form.platformName}</p>
              )}
            </div>
          </PreviewCard>

          <PreviewCard title="Email Footer" titleAr="تذييل البريد">
            <div
              className="rounded-lg border bg-white p-3 text-sm"
              dangerouslySetInnerHTML={{ __html: emailFooter || "<p class='text-muted-foreground'>—</p>" }}
            />
          </PreviewCard>
        </div>
      </div>
    </PageLayout>
  );
}

function PreviewCard({
  title,
  titleAr,
  children,
}: {
  title: string;
  titleAr: string;
  children: React.ReactNode;
}) {
  return (
    <div className="surface-elevated p-4">
      <h3 className="text-sm font-semibold">
        {titleAr}{" "}
        <span className="text-xs font-normal text-muted-foreground">({title})</span>
      </h3>
      <div className="mt-3">{children}</div>
    </div>
  );
}
