"use client";

import { useState, type FormEvent } from "react";
import type { GeneralSettings } from "@/types/settings";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { useToast } from "@/components/ui/toast";
import { clientFetch } from "@/lib/api/client";
import { MediaSlot } from "./media-slot";

export function GeneralSettingsForm({ initial }: { initial: GeneralSettings }) {
  const [platformName, setPlatformName] = useState(initial.platform_name);
  const [footerCopyrightText, setFooterCopyrightText] = useState(initial.footer_copyright_text ?? "");
  const [message, setMessage] = useState<string | null>(null);
  const [error, setError] = useState<string | null>(null);
  const [isSubmitting, setIsSubmitting] = useState(false);
  const { toast } = useToast();

  async function handleSubmit(formEvent: FormEvent<HTMLFormElement>) {
    formEvent.preventDefault();
    setMessage(null);
    setError(null);
    setIsSubmitting(true);

    const res = await clientFetch("/api/admin/settings/general", {
      method: "PUT",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({
        platform_name: platformName,
        footer_copyright_text: footerCopyrightText || null,
      }),
    });

    setIsSubmitting(false);
    const body = await res.json().catch(() => null);

    if (!res.ok) {
      const errorMessage = body?.message ?? "Failed to save general settings.";
      setError(errorMessage);
      toast(errorMessage, "error");
      return;
    }

    const successMessage = body?.message ?? "Saved.";
    setMessage(successMessage);
    toast(successMessage, "success");
  }

  return (
    <form onSubmit={handleSubmit} className="mt-3 flex flex-col gap-3">
      <label className="flex flex-col gap-1 text-sm font-medium">
        Platform Name
        <Input required value={platformName} onChange={(e) => setPlatformName(e.target.value)} />
      </label>
      <MediaSlot
        label="Platform Logo"
        fieldName="logo"
        endpoint="/api/admin/settings/general/logo/platform"
        current={initial.platform_logo}
        hint="JPG/PNG/WEBP, max 5MB."
      />

      <div className="mt-2 border-t border-kolabora-neutral-dark/10 pt-3">
        <p className="text-sm font-medium">Navbar &amp; Footer</p>
        <div className="mt-3 flex flex-col gap-4">
          <MediaSlot
            label="Navbar Logo"
            fieldName="logo"
            endpoint="/api/admin/settings/general/logo/navbar"
            current={initial.navbar_logo_url}
            hint="Shown top-left on every page. Leave empty to use the default logo."
          />
          <MediaSlot
            label="Footer Logo"
            fieldName="logo"
            endpoint="/api/admin/settings/general/logo/footer"
            current={initial.footer_logo_url}
            hint="Shown in the footer (dark background) — usually a white/monochrome variant. Leave empty to use the default &quot;Kolaborativ&quot; text."
          />
          <label className="flex flex-col gap-1 text-sm font-medium">
            Footer Copyright Text
            <Input
              value={footerCopyrightText}
              onChange={(e) => setFooterCopyrightText(e.target.value)}
              placeholder={`© ${new Date().getFullYear()} Kolaborativ. All rights reserved.`}
            />
            <span className="text-xs font-normal text-kolabora-neutral-dark/70">
              Leave empty to use the default text with the current year filled in automatically.
            </span>
          </label>
        </div>
      </div>

      {message && <p className="text-sm text-green-600">{message}</p>}
      {error && <p className="text-sm text-red-600">{error}</p>}
      <Button type="submit" loading={isSubmitting} className="mt-1 self-start">
        Save
      </Button>
    </form>
  );
}
