"use client";
import { useState } from "react";
import type { CmsSettings } from "@/lib/cms/client-types";
import { MediaLibrary } from "./media-library";
export function SeoSettings({ initial }: { initial: CmsSettings }) {
  const [settings, setSettings] = useState(initial),
    [busy, setBusy] = useState(false),
    [message, setMessage] = useState(""),
    [error, setError] = useState(""),
    [picker, setPicker] = useState(false);
  return (
    <form
      className="admin-settings-form"
      onSubmit={async (event) => {
        event.preventDefault();
        setBusy(true);
        setError("");
        setMessage("");
        try {
          const response = await fetch("/api/admin/settings/", {
            method: "PUT",
            headers: { "Content-Type": "application/json" },
            body: JSON.stringify(settings),
          });
          const data = await response.json();
          if (!response.ok) throw new Error(data.error);
          setMessage("Site settings saved.");
        } catch (error) {
          setError(error instanceof Error ? error.message : "Unable to save");
        } finally {
          setBusy(false);
        }
      }}
    >
      <div className="admin-card admin-fields">
        <h2>Search appearance</h2>
        <label>
          Website name
          <input
            value={settings.siteName}
            required
            minLength={3}
            maxLength={120}
            onChange={(e) =>
              setSettings({ ...settings, siteName: e.target.value })
            }
          />
        </label>
        <label>
          Default search description
          <textarea
            rows={4}
            required
            minLength={10}
            maxLength={500}
            value={settings.description}
            onChange={(e) =>
              setSettings({ ...settings, description: e.target.value })
            }
          />
        </label>
        <label>
          Website address
          <input
            type="url"
            required
            value={settings.siteUrl}
            onChange={(e) =>
              setSettings({
                ...settings,
                siteUrl: e.target.value.replace(/\/$/, ""),
              })
            }
          />
          <small>
            Use your public HTTPS domain when you launch. Canonical URLs and the
            sitemap use this address.
          </small>
        </label>
        <label className="admin-checkbox">
          <input
            type="checkbox"
            checked={settings.allowIndexing}
            onChange={(e) =>
              setSettings({ ...settings, allowIndexing: e.target.checked })
            }
          />
          Allow search engine indexing
        </label>
        <p className="admin-small">
          Local development stays private to search engines. At launch, also set
          NEXT_PUBLIC_ALLOW_INDEXING=true in your hosting environment and
          rebuild.
        </p>
      </div>
      <div className="admin-card admin-fields">
        <h2>Social sharing</h2>
        {settings.socialImage && (
          <img
            className="admin-social-image"
            src={settings.socialImage}
            alt="Default social sharing image"
          />
        )}
        <button
          className="admin-button secondary"
          type="button"
          onClick={() => setPicker(!picker)}
        >
          Choose sharing image
        </button>
        {picker && (
          <MediaLibrary
            onSelect={(image) => {
              setSettings({ ...settings, socialImage: image.url });
              setPicker(false);
            }}
          />
        )}
        <div className="admin-search-preview">
          <small>{settings.siteUrl}</small>
          <strong>{settings.siteName}</strong>
          <p>{settings.description}</p>
        </div>
      </div>
      {message && (
        <p className="admin-success" role="status">
          {message}
        </p>
      )}
      {error && (
        <p className="admin-error" role="alert">
          {error}
        </p>
      )}
      <button className="admin-button" disabled={busy}>
        {busy ? "Saving…" : "Save SEO settings"}
      </button>
    </form>
  );
}
export function AccountSettings() {
  const [currentPassword, setCurrent] = useState(""),
    [newPassword, setNew] = useState(""),
    [busy, setBusy] = useState(false),
    [message, setMessage] = useState(""),
    [error, setError] = useState("");
  return (
    <>
      <form
        className="admin-card admin-fields admin-account-form"
        onSubmit={async (e) => {
          e.preventDefault();
          setBusy(true);
          setError("");
          setMessage("");
          try {
            const response = await fetch("/api/admin/password/", {
              method: "POST",
              headers: { "Content-Type": "application/json" },
              body: JSON.stringify({
                current: currentPassword,
                password: newPassword,
              }),
            });
            const data = await response.json();
            if (!response.ok) throw new Error(data.error);
            setCurrent("");
            setNew("");
            setMessage(
              "Password changed. Other sessions have been signed out.",
            );
          } catch (error) {
            setError(
              error instanceof Error
                ? error.message
                : "Unable to update password",
            );
          } finally {
            setBusy(false);
          }
        }}
      >
        <h2>Your password</h2>
        <label>
          Current password
          <input
            required
            type="password"
            autoComplete="current-password"
            value={currentPassword}
            onChange={(e) => setCurrent(e.target.value)}
          />
        </label>
        <label>
          New password
          <input
            required
            type="password"
            autoComplete="new-password"
            minLength={12}
            maxLength={256}
            value={newPassword}
            onChange={(e) => setNew(e.target.value)}
          />
          <small>Use at least 12 characters.</small>
        </label>
        {message && (
          <p className="admin-success" role="status">
            {message}
          </p>
        )}
        {error && (
          <p className="admin-error" role="alert">
            {error}
          </p>
        )}
        <button className="admin-button" disabled={busy}>
          {busy ? "Updating…" : "Change password"}
        </button>
      </form>
      <section className="admin-card">
        <h2>Content backup</h2>
        <p>
          Download articles, working copies, revisions, redirects, media details
          and SEO settings. Keep a separate copy of the uploaded image files in
          .local/uploads and a full MySQL dump for disaster recovery.
        </p>
        <a className="admin-button secondary" href="/api/blog/export/">
          Download content backup
        </a>
      </section>
    </>
  );
}
