import type { Metadata } from "next";
import {
  Settings as SettingsIcon,
  Megaphone,
  Wrench,
  Mail,
  Search,
  AlertTriangle,
} from "lucide-react";
import { Button } from "@/components/Button";
import {
  AdminHeading,
  FormSection,
  InputField,
  TextareaField,
} from "@/components/admin";
import { loadSiteSettings } from "@/lib/settings";
import { updateSiteSettings } from "./actions";

export const metadata: Metadata = { title: "Settings" };
export const dynamic = "force-dynamic";

export default async function AdminSettingsPage() {
  const settings = await loadSiteSettings();

  return (
    <>
      <AdminHeading
        eyebrow="Overview"
        title="Settings"
        lede="Site-wide brand, contact, membership SLA, and feature toggles. Changes apply immediately across the public site."
      />

      <form action={updateSiteSettings} className="flex flex-col gap-6">
        <FormSection
          title="Brand"
          description="Displayed across the site header, meta tags, and open-graph cards."
        >
          <div className="grid gap-4 md:grid-cols-2">
            <InputField
              label="Site name"
              name="siteName"
              defaultValue={settings.siteName}
              required
              maxLength={100}
            />
            <InputField
              label="Tagline"
              name="tagline"
              defaultValue={settings.tagline}
              maxLength={200}
            />
          </div>
        </FormSection>

        <FormSection title="Contact" description="Where public visitors reach the team.">
          <div className="grid gap-4 md:grid-cols-2">
            <InputField
              label="Contact email"
              name="contactEmail"
              type="email"
              defaultValue={settings.contactEmail}
              required
              maxLength={200}
            />
          </div>
        </FormSection>

        <FormSection
          title="Membership"
          description="Application intake and review timing shown to applicants."
        >
          <div className="grid gap-4 md:grid-cols-2">
            <InputField
              label="Review SLA (hours)"
              name="reviewSlaHours"
              type="number"
              min={1}
              max={720}
              defaultValue={String(settings.reviewSlaHours)}
              hint="Shown on /join as the review turnaround."
            />
            <label className="flex items-end gap-2.5 text-[14px]">
              <input
                type="checkbox"
                name="applicationsOpen"
                defaultChecked={settings.applicationsOpen}
                className="mb-2 h-4 w-4 rounded border-[var(--color-line)] text-[var(--color-blue)]"
              />
              <span className="mb-2">
                <span className="block font-semibold text-[var(--color-ink)]">
                  Applications open
                </span>
                <span className="block text-[12px] text-[var(--color-slate)]">
                  Unchecked means the Join form is disabled with a closed-notice.
                </span>
              </span>
            </label>
          </div>
        </FormSection>

        <FormSection
          title="Maintenance mode"
          description="Hide every page except /maintenance behind a notice. Admin routes remain reachable."
          tone="danger"
        >
          <div className="grid gap-4">
            <label className="flex items-start gap-2.5 text-[14px]">
              <input
                type="checkbox"
                name="maintenanceMode"
                defaultChecked={settings.maintenanceMode}
                className="mt-0.5 h-4 w-4 rounded border-[var(--color-line)] text-[var(--color-blue)]"
              />
              <span>
                <span className="block font-semibold text-[var(--color-ink)]">
                  Enable maintenance mode
                </span>
                <span className="block text-[12px] text-[var(--color-slate)]">
                  Logged-in admins continue to see the full site.
                </span>
              </span>
            </label>
            <TextareaField
              label="Maintenance message"
              name="maintenanceMessage"
              defaultValue={settings.maintenanceMessage}
              rows={3}
              maxLength={500}
            />
            <div className="flex items-start gap-2 rounded-md border border-red-200 bg-red-50 p-3 text-[12px] text-red-900">
              <AlertTriangle className="mt-0.5 h-4 w-4 shrink-0" aria-hidden />
              <div>
                <p className="font-semibold">
                  Turning on maintenance mode hides the public site.
                </p>
                <p className="mt-0.5">
                  To confirm, type <code className="font-mono">ENABLE MAINTENANCE</code> below.
                  Leave blank to keep maintenance mode off.
                </p>
              </div>
            </div>
            <InputField
              label="Confirmation"
              name="maintenanceConfirm"
              placeholder="ENABLE MAINTENANCE"
              maxLength={30}
              hint="Only required when flipping maintenance mode ON."
            />
          </div>
        </FormSection>

        <FormSection
          title="Search engine optimisation"
          description="Defaults applied to pages that don't set their own metadata."
        >
          <div className="grid gap-4 md:grid-cols-2">
            <InputField
              label="Default title"
              name="seoDefaultTitle"
              defaultValue={settings.seoDefaultTitle}
              maxLength={200}
              hint="Shown in browser tabs and search results on the home page."
            />
            <InputField
              label="Title template"
              name="seoTitleTemplate"
              defaultValue={settings.seoTitleTemplate}
              maxLength={200}
              hint="%s is replaced by the page title."
            />
            <TextareaField
              label="Default description"
              name="seoDefaultDescription"
              defaultValue={settings.seoDefaultDescription}
              rows={2}
              maxLength={400}
              wrapClassName="md:col-span-2"
            />
            <InputField
              label="Keywords"
              name="seoKeywords"
              defaultValue={settings.seoKeywords}
              maxLength={400}
              hint="Comma-separated."
              wrapClassName="md:col-span-2"
            />
            <InputField
              label="Open Graph image path"
              name="seoOgImage"
              defaultValue={settings.seoOgImage}
              maxLength={500}
            />
            <InputField
              label="Twitter handle"
              name="seoTwitterHandle"
              defaultValue={settings.seoTwitterHandle}
              maxLength={100}
              placeholder="@orthoglobe"
            />
            <InputField
              label="Robots"
              name="seoRobots"
              defaultValue={settings.seoRobots}
              maxLength={100}
              hint="e.g. index,follow — set noindex to hide from search engines."
              wrapClassName="md:col-span-2"
            />
          </div>
        </FormSection>

        <FormSection
          title="Site features"
          description="Quick toggles for cross-cutting UI."
        >
          <label className="flex items-start gap-2.5 text-[14px]">
            <input
              type="checkbox"
              name="announcementBarEnabled"
              defaultChecked={settings.announcementBarEnabled}
              className="mt-0.5 h-4 w-4 rounded border-[var(--color-line)] text-[var(--color-blue)]"
            />
            <span>
              <span className="block font-semibold text-[var(--color-ink)]">
                Show notification banner
              </span>
              <span className="block text-[12px] text-[var(--color-slate)]">
                When off, every active notification in the DB is hidden from
                public pages regardless of individual scheduling.
              </span>
            </span>
          </label>
        </FormSection>

        <div className="sticky bottom-4 flex flex-wrap items-center justify-between gap-3 rounded-xl border border-[var(--color-line)] bg-white p-4 shadow-[0_16px_40px_rgba(10,15,46,0.06)]">
          <div className="flex items-center gap-2 text-[12px] text-[var(--color-slate)]">
            <SettingsIcon className="h-4 w-4 text-[var(--color-blue)]" aria-hidden />
            Settings apply site-wide immediately on save.
          </div>
          <Button type="submit" variant="primary" className="!px-5 !py-2 !text-[13px]">
            Save settings
          </Button>
        </div>
      </form>

      <div className="mt-10 grid gap-4 md:grid-cols-4">
        <InfoTile
          Icon={Mail}
          title="Email delivery"
          body="Membership emails, notifications, and rejection notes are delivered via the configured mailer in .env."
        />
        <InfoTile
          Icon={Megaphone}
          title="Notification banners"
          body="Manage individual scheduled banners at /admin/notifications. Use the global toggle above for site-wide mute."
        />
        <InfoTile
          Icon={Wrench}
          title="Maintenance"
          body="Maintenance mode leaves /admin and /api routes working so you can continue to fix things while public traffic sees a notice."
        />
        <InfoTile
          Icon={Search}
          title="SEO"
          body="Defaults apply when a page doesn't set its own meta title or description. Use 'noindex' in robots to de-list staging sites."
        />
      </div>
    </>
  );
}

function InfoTile({
  Icon,
  title,
  body,
}: {
  Icon: typeof SettingsIcon;
  title: string;
  body: string;
}) {
  return (
    <div className="rounded-xl border border-[var(--color-line)] bg-[var(--color-line)]/20 p-4">
      <div className="flex items-center gap-2 text-[11px] font-bold uppercase tracking-wider text-[var(--color-blue)]">
        <Icon className="h-3.5 w-3.5" aria-hidden />
        {title}
      </div>
      <p className="mt-2 text-[13px] leading-relaxed text-[var(--color-slate)]">
        {body}
      </p>
    </div>
  );
}
