"use client";

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

export default function AdminStripeSettingsPage() {
  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(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({
          stripeEnabled: form.stripeEnabled,
          stripePublishableKey: form.stripePublishableKey,
          stripeSecretKey: form.stripeSecretKey,
        }),
      });
      const data = (await res.json()) as {
        settings?: SiteSettingsDTO;
        error?: string;
      };
      if (!res.ok || !data.settings) {
        toast(data.error ?? "Could not save Stripe settings", "error");
        return;
      }
      setForm(data.settings);
      toast("Stripe settings saved");
    } finally {
      setSaving(false);
    }
  };

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

  return (
    <form onSubmit={onSave} className="mx-auto max-w-2xl space-y-8">
      <div>
        <h1 className="text-2xl font-semibold text-foreground">Stripe payments</h1>
        <p className="mt-1 text-sm text-muted">
          Enable live Stripe checkout with your publishable and secret keys.
          Keys are stored in MariaDB for this store.
        </p>
      </div>

      <section className="space-y-4 rounded-2xl border border-border bg-card p-5">
        <label className="flex items-center gap-3 rounded-xl border border-border bg-surface px-4 py-3 text-sm text-foreground">
          <input
            type="checkbox"
            checked={form.stripeEnabled}
            onChange={(event) =>
              setForm({ ...form, stripeEnabled: event.target.checked })
            }
            className="accent-emerald-500"
          />
          Enable Stripe checkout
        </label>
        <label className="block space-y-1.5 text-sm">
          <span className="text-muted">Publishable key</span>
          <input
            value={form.stripePublishableKey}
            onChange={(event) =>
              setForm({ ...form, stripePublishableKey: event.target.value })
            }
            placeholder="pk_test_…"
            className="h-11 w-full rounded-xl border border-border bg-background px-3 text-sm text-foreground outline-none focus:border-emerald-500/50"
          />
        </label>
        <label className="block space-y-1.5 text-sm">
          <span className="text-muted">Secret key</span>
          <input
            type="password"
            value={form.stripeSecretKey}
            onChange={(event) =>
              setForm({ ...form, stripeSecretKey: event.target.value })
            }
            placeholder="sk_test_…"
            className="h-11 w-full rounded-xl border border-border bg-background px-3 text-sm text-foreground outline-none focus:border-emerald-500/50"
          />
        </label>
        <p className="text-xs leading-relaxed text-muted">
          Tip: you can still use <code className="text-foreground">.env</code>{" "}
          keys as fallback. Admin-saved keys take priority when Stripe is
          enabled here.
        </p>
        <div className="rounded-xl border border-border bg-surface px-4 py-3 text-xs leading-relaxed text-muted">
          <p className="font-medium text-foreground">What Stripe receives</p>
          <p className="mt-1">
            Every payment syncs each cart product into Stripe (name, images,
            category, seller, tags, slug) and attaches a product line table on
            the PaymentIntent with unit price, quantity, and product codes —
            plus shipping, discount, and order metadata.
          </p>
          <p className="mt-2">
            Optional webhook: set{" "}
            <code className="text-foreground">STRIPE_WEBHOOK_SECRET</code> and
            point Stripe to{" "}
            <code className="text-foreground">/api/webhooks/stripe</code> for
            <code className="text-foreground"> payment_intent.succeeded</code>.
          </p>
        </div>
      </section>

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