"use client";

import { useEffect, useState, type FormEvent } from "react";
import { Button } from "@/components/ui/Button";
import { MediaUploader } from "@/components/admin/MediaUploader";
import { useToast } from "@/context/toast-context";
import {
  defaultSettings,
  type SiteSettingsDTO,
} from "@/lib/settings-shared";

export default function AdminGeneralSettingsPage() {
  const { toast } = useToast();
  const [form, setForm] = useState<SiteSettingsDTO | null>(null);
  const [saving, setSaving] = useState(false);

  useEffect(() => {
    void fetch("/api/admin/settings", { credentials: "include" })
      .then((res) => res.json())
      .then((data: { settings?: SiteSettingsDTO }) => {
        if (data.settings) {
          setForm({ ...defaultSettings, ...data.settings });
        }
      });
  }, []);

  const onSave = async (event: FormEvent) => {
    event.preventDefault();
    if (!form) return;
    setSaving(true);
    try {
      const res = await fetch("/api/admin/settings", {
        method: "PATCH",
        headers: { "Content-Type": "application/json" },
        credentials: "include",
        body: JSON.stringify({
          siteName: form.siteName,
          tagline: form.tagline,
          description: form.description,
          logoUrl: form.logoUrl,
          faviconUrl: form.faviconUrl,
          supportEmail: form.supportEmail,
          supportPhone: form.supportPhone,
          address: form.address,
          facebookUrl: form.facebookUrl,
          instagramUrl: form.instagramUrl,
          twitterUrl: form.twitterUrl,
          youtubeUrl: form.youtubeUrl,
          tiktokUrl: form.tiktokUrl,
          currency: form.currency,
          footerTagline: form.footerTagline,
          footerNote: form.footerNote,
        }),
      });
      let data: { settings?: SiteSettingsDTO; error?: string } = {};
      try {
        data = (await res.json()) as {
          settings?: SiteSettingsDTO;
          error?: string;
        };
      } catch {
        toast(
          res.ok
            ? "Saved, but the server returned an invalid response"
            : `Save failed (HTTP ${res.status})`,
          "error",
        );
        return;
      }
      if (!res.ok || !data.settings) {
        toast(data.error ?? `Could not save settings (HTTP ${res.status})`, "error");
        return;
      }
      setForm({ ...defaultSettings, ...data.settings });
      toast("Site settings saved");
    } catch {
      toast("Network error while saving settings", "error");
    } finally {
      setSaving(false);
    }
  };

  if (!form) {
    return <p className="text-sm text-muted">Loading settings…</p>;
  }

  return (
    <form onSubmit={onSave} className="mx-auto max-w-3xl space-y-8">
      <div>
        <h1 className="text-2xl font-semibold text-foreground">
          General & branding
        </h1>
        <p className="mt-1 text-sm text-muted">
          Logo, favicon, contact details, and social links used across the store.
        </p>
      </div>

      <section className="space-y-4 rounded-2xl border border-border bg-card p-5">
        <Field
          label="Site name"
          value={form.siteName}
          onChange={(siteName) => setForm({ ...form, siteName })}
        />
        <Field
          label="Tagline"
          value={form.tagline}
          onChange={(tagline) => setForm({ ...form, tagline })}
        />
        <Field
          label="SEO / meta description"
          value={form.description}
          onChange={(description) => setForm({ ...form, description })}
          textarea
        />
        <div className="grid gap-4 sm:grid-cols-2">
          <Field
            label="Currency"
            value={form.currency}
            onChange={(currency) => setForm({ ...form, currency })}
          />
        </div>
      </section>

      <section className="space-y-4 rounded-2xl border border-border bg-card p-5">
        <div>
          <h2 className="text-sm font-semibold text-foreground">
            Contact details
          </h2>
          <p className="mt-1 text-xs text-muted">
            Phone + email appear in the top header. Phone, email, and address
            appear in the footer, Contact, and About pages.
          </p>
        </div>
        <div className="grid gap-4 sm:grid-cols-2">
          <Field
            label="Support phone (header + footer)"
            value={form.supportPhone}
            onChange={(supportPhone) => setForm({ ...form, supportPhone })}
          />
          <Field
            label="Support email (header + footer)"
            value={form.supportEmail}
            onChange={(supportEmail) => setForm({ ...form, supportEmail })}
          />
        </div>
        <Field
          label="Store address (footer, Contact, About)"
          value={form.address}
          onChange={(address) => setForm({ ...form, address })}
          textarea
        />
      </section>

      <section className="space-y-4 rounded-2xl border border-border bg-card p-5">
        <div>
          <h2 className="text-sm font-semibold text-foreground">Social links</h2>
          <p className="mt-1 text-xs text-muted">
            Leave blank to hide an icon. Shown in footer, Contact, and About.
          </p>
        </div>
        <div className="grid gap-4 sm:grid-cols-2">
          <Field
            label="Facebook URL"
            value={form.facebookUrl}
            onChange={(facebookUrl) => setForm({ ...form, facebookUrl })}
          />
          <Field
            label="Instagram URL"
            value={form.instagramUrl}
            onChange={(instagramUrl) => setForm({ ...form, instagramUrl })}
          />
          <Field
            label="X / Twitter URL"
            value={form.twitterUrl}
            onChange={(twitterUrl) => setForm({ ...form, twitterUrl })}
          />
          <Field
            label="YouTube URL"
            value={form.youtubeUrl}
            onChange={(youtubeUrl) => setForm({ ...form, youtubeUrl })}
          />
          <Field
            label="TikTok URL"
            value={form.tiktokUrl}
            onChange={(tiktokUrl) => setForm({ ...form, tiktokUrl })}
          />
        </div>
      </section>

      <section className="space-y-4 rounded-2xl border border-border bg-card p-5">
        <div>
          <h2 className="text-sm font-semibold text-foreground">Footer copy</h2>
        </div>
        <Field
          label="Footer tagline"
          value={form.footerTagline}
          onChange={(footerTagline) => setForm({ ...form, footerTagline })}
          textarea
        />
        <Field
          label="Footer note (use · to separate items)"
          value={form.footerNote}
          onChange={(footerNote) => setForm({ ...form, footerNote })}
        />
      </section>

      <section className="space-y-6 rounded-2xl border border-border bg-card p-5">
        <MediaUploader
          label="Logo"
          single
          max={1}
          folder="branding"
          images={form.logoUrl ? [form.logoUrl] : []}
          onChange={(images) =>
            setForm({ ...form, logoUrl: images[0] ?? "" })
          }
        />
        <MediaUploader
          label="Favicon"
          single
          max={1}
          folder="branding"
          images={form.faviconUrl ? [form.faviconUrl] : []}
          onChange={(images) =>
            setForm({ ...form, faviconUrl: images[0] ?? "/favicon.svg" })
          }
        />
        <p className="text-xs text-muted">
          Defaults: typographic BhoFit wordmark and{" "}
          <code>/favicon.svg</code>
        </p>
      </section>

      <div className="flex justify-end">
        <Button type="submit" disabled={saving} className="h-11 rounded-xl">
          {saving ? "Saving…" : "Save settings"}
        </Button>
      </div>
    </form>
  );
}

function Field({
  label,
  value,
  onChange,
  textarea,
}: {
  label: string;
  value: string;
  onChange: (value: string) => void;
  textarea?: boolean;
}) {
  const className =
    "w-full rounded-xl border border-border bg-background px-3 text-sm text-foreground outline-none focus:border-[var(--brand-blue)]/50";
  return (
    <label className="block space-y-1.5 text-sm">
      <span className="text-muted">{label}</span>
      {textarea ? (
        <textarea
          value={value}
          onChange={(event) => onChange(event.target.value)}
          rows={3}
          className={`${className} py-2.5`}
        />
      ) : (
        <input
          value={value}
          onChange={(event) => onChange(event.target.value)}
          className={`${className} h-11`}
        />
      )}
    </label>
  );
}
