"use client";

import { useState, useTransition } from "react";
import {
  Building2, CreditCard, Mail, Share2, Lock,
  CheckCircle, XCircle, Eye, EyeOff,
  AlertTriangle, ShieldCheck, Loader2,
} from "lucide-react";
import {
  saveCompanySettings,
  saveSocialSettings,
  saveStripeSettings,
  saveEmailSettings,
  saveTesterSettings,
} from "./actions";

type Settings = Record<string, string>;

const TABS = [
  { id: "company",  label: "Company",  icon: Building2 },
  { id: "payment",  label: "Payment",  icon: CreditCard },
  { id: "email",    label: "Email",    icon: Mail },
  { id: "social",   label: "Social & Contact", icon: Share2 },
  { id: "access",   label: "Access Control",   icon: Lock },
] as const;

type TabId = (typeof TABS)[number]["id"];

// ── Reusable field components ─────────────────────────────────────────────────

function Field({ label, hint, children }: { label: string; hint?: string; children: React.ReactNode }) {
  return (
    <div>
      <label className="block text-xs font-semibold text-neutral-500 uppercase tracking-wide mb-1.5">{label}</label>
      {children}
      {hint && <p className="text-xs text-neutral-400 mt-1">{hint}</p>}
    </div>
  );
}

function Input({ name, defaultValue, placeholder, type = "text" }: {
  name: string; defaultValue?: string; placeholder?: string; type?: string;
}) {
  return (
    <input
      name={name}
      type={type}
      defaultValue={defaultValue}
      placeholder={placeholder}
      className="w-full border border-neutral-300 rounded-lg px-3 py-2.5 text-sm focus:outline-none focus:border-navy-500 focus:ring-1 focus:ring-navy-100"
    />
  );
}

function Select({ name, defaultValue, children }: {
  name: string; defaultValue?: string; children: React.ReactNode;
}) {
  return (
    <select
      name={name}
      defaultValue={defaultValue}
      className="w-full border border-neutral-300 rounded-lg px-3 py-2.5 text-sm focus:outline-none focus:border-navy-500 bg-white"
    >
      {children}
    </select>
  );
}

function SecretInput({ name, defaultValue, placeholder }: { name: string; defaultValue?: string; placeholder?: string }) {
  const [show, setShow] = useState(false);
  return (
    <div className="relative">
      <input
        name={name}
        type={show ? "text" : "password"}
        defaultValue={defaultValue}
        placeholder={placeholder}
        className="w-full border border-neutral-300 rounded-lg px-3 py-2.5 pr-10 text-sm font-mono focus:outline-none focus:border-navy-500 focus:ring-1 focus:ring-navy-100"
      />
      <button type="button" onClick={() => setShow(v => !v)} tabIndex={-1}
        className="absolute right-3 top-1/2 -translate-y-1/2 text-neutral-400 hover:text-neutral-600">
        {show ? <EyeOff size={15} /> : <Eye size={15} />}
      </button>
    </div>
  );
}

function SectionCard({ title, description, children }: {
  title: string; description?: string; children: React.ReactNode;
}) {
  return (
    <div className="bg-white rounded-2xl border border-neutral-200 overflow-hidden">
      <div className="px-6 py-4 border-b border-neutral-100">
        <h3 className="font-semibold text-neutral-800">{title}</h3>
        {description && <p className="text-xs text-neutral-400 mt-0.5">{description}</p>}
      </div>
      <div className="p-6">{children}</div>
    </div>
  );
}

function SaveButton({ pending }: { pending: boolean }) {
  return (
    <button
      type="submit"
      disabled={pending}
      className="flex items-center gap-2 px-5 py-2.5 bg-navy-700 hover:bg-navy-800 text-white text-sm font-semibold rounded-lg transition-colors disabled:opacity-60"
    >
      {pending ? <><Loader2 size={14} className="animate-spin" /> Saving…</> : "Save Changes"}
    </button>
  );
}

// ── Toast ─────────────────────────────────────────────────────────────────────

function useToast() {
  const [msg, setMsg] = useState<{ type: "ok" | "err"; text: string } | null>(null);
  function show(type: "ok" | "err", text: string) {
    setMsg({ type, text });
    setTimeout(() => setMsg(null), 4000);
  }
  const Toast = msg ? (
    <div className={`fixed bottom-6 right-6 z-50 flex items-center gap-2.5 px-4 py-3 rounded-xl shadow-lg text-sm font-medium border transition-all ${
      msg.type === "ok"
        ? "bg-emerald-50 text-emerald-800 border-emerald-200"
        : "bg-red-50 text-red-700 border-red-200"
    }`}>
      {msg.type === "ok" ? <CheckCircle size={16} /> : <XCircle size={16} />}
      {msg.text}
    </div>
  ) : null;
  return { show, Toast };
}

// ── Main Component ────────────────────────────────────────────────────────────

export default function AdminSettingsClient({ settings: s }: { settings: Settings }) {
  const [tab, setTab] = useState<TabId>("company");
  const [isPending, startTransition] = useTransition();
  const { show, Toast } = useToast();

  function handle(action: (fd: FormData) => Promise<void>, successMsg: string) {
    return (e: React.FormEvent<HTMLFormElement>) => {
      e.preventDefault();
      const fd = new FormData(e.currentTarget);
      startTransition(async () => {
        try {
          await action(fd);
          show("ok", successMsg);
        } catch {
          show("err", "Failed to save. Please try again.");
        }
      });
    };
  }

  const [stripeMode, setStripeMode] = useState<"live" | "sandbox">(
    (s["stripe_mode"] as "live" | "sandbox") ?? "sandbox"
  );
  const [testerMode, setTesterMode] = useState<"true" | "false">(
    (s["tester_mode"] as "true" | "false") ?? "false"
  );

  return (
    <div className="min-h-screen bg-neutral-50">
      {Toast}

      {/* Page header */}
      <div className="bg-white border-b border-neutral-200 px-8 py-6">
        <h1 className="text-2xl font-bold text-neutral-900">Settings</h1>
        <p className="text-neutral-500 text-sm mt-0.5">Manage your platform configuration.</p>
      </div>

      <div className="flex">
        {/* Sidebar tabs */}
        <aside className="w-56 shrink-0 bg-white border-r border-neutral-200 min-h-[calc(100vh-105px)] p-3 space-y-1">
          {TABS.map(({ id, label, icon: Icon }) => (
            <button
              key={id}
              onClick={() => setTab(id)}
              className={`w-full flex items-center gap-3 px-3 py-2.5 rounded-xl text-sm font-medium transition-colors text-left ${
                tab === id
                  ? "bg-navy-700 text-white"
                  : "text-neutral-600 hover:bg-neutral-100"
              }`}
            >
              <Icon size={16} className="shrink-0" />
              {label}
            </button>
          ))}
        </aside>

        {/* Tab content */}
        <main className="flex-1 p-8 space-y-6 max-w-3xl">

          {/* ── COMPANY ── */}
          {tab === "company" && (
            <>
              <form onSubmit={handle(saveCompanySettings, "Company settings saved.")} className="space-y-6">
                <SectionCard title="Brand" description="Your platform name, logo, and identity.">
                  <div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
                    <Field label="Site Name">
                      <Input name="site_name" defaultValue={s["site_name"]} placeholder="KC Systems Limited" />
                    </Field>
                    <Field label="Tagline">
                      <Input name="site_tagline" defaultValue={s["site_tagline"]} placeholder="Short description of your platform" />
                    </Field>
                    <Field label="Logo URL" hint="Full URL to your logo image (PNG/SVG recommended).">
                      <Input name="site_logo_url" defaultValue={s["site_logo_url"]} placeholder="https://…/logo.png" />
                    </Field>
                    <Field label="Favicon URL" hint="32×32 or 64×64 ICO/PNG.">
                      <Input name="site_favicon_url" defaultValue={s["site_favicon_url"]} placeholder="https://…/favicon.ico" />
                    </Field>
                  </div>
                </SectionCard>

                <SectionCard title="Contact & Location" description="How users and systems reach you.">
                  <div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
                    <Field label="Admin Email" hint="System notifications sent here.">
                      <Input name="admin_email" type="email" defaultValue={s["admin_email"]} placeholder="admin@kcsystems.com" />
                    </Field>
                    <Field label="Support Email" hint="Shown to users for help inquiries.">
                      <Input name="support_email" type="email" defaultValue={s["support_email"]} placeholder="support@kcsystems.com" />
                    </Field>
                    <Field label="Phone Number">
                      <Input name="site_phone" defaultValue={s["site_phone"]} placeholder="+60 12-345 6789" />
                    </Field>
                    <Field label="Country">
                      <Input name="site_country" defaultValue={s["site_country"]} placeholder="Malaysia" />
                    </Field>
                    <div className="sm:col-span-2">
                      <Field label="Business Address">
                        <Input name="site_address" defaultValue={s["site_address"]} placeholder="123 Jalan Example, Kuala Lumpur" />
                      </Field>
                    </div>
                  </div>
                </SectionCard>

                <SectionCard title="Regional" description="Timezone and currency defaults.">
                  <div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
                    <Field label="Timezone">
                      <Select name="site_timezone" defaultValue={s["site_timezone"] || "Asia/Kuala_Lumpur"}>
                        <option value="Asia/Kuala_Lumpur">Asia/Kuala_Lumpur (MYT, UTC+8)</option>
                        <option value="Africa/Lagos">Africa/Lagos (WAT, UTC+1)</option>
                        <option value="Europe/London">Europe/London (GMT/BST)</option>
                        <option value="America/New_York">America/New_York (ET)</option>
                        <option value="UTC">UTC</option>
                      </Select>
                    </Field>
                    <Field label="Default Currency">
                      <Select name="site_currency" defaultValue={s["site_currency"] || "USD"}>
                        <option value="USD">USD — US Dollar</option>
                        <option value="MYR">MYR — Malaysian Ringgit</option>
                        <option value="NGN">NGN — Nigerian Naira</option>
                        <option value="GBP">GBP — British Pound</option>
                        <option value="EUR">EUR — Euro</option>
                      </Select>
                    </Field>
                  </div>
                </SectionCard>

                <div className="flex justify-end">
                  <SaveButton pending={isPending} />
                </div>
              </form>
            </>
          )}

          {/* ── PAYMENT ── */}
          {tab === "payment" && (
            <form onSubmit={handle(saveStripeSettings, "Stripe settings saved.")} className="space-y-6">
              <SectionCard title="Active Mode" description="Controls which Stripe keys are used for all transactions.">
                <div className="flex gap-3">
                  {(["sandbox", "live"] as const).map((m) => (
                    <label
                      key={m}
                      className={`flex-1 flex items-center gap-3 px-5 py-4 rounded-xl border-2 cursor-pointer transition-all ${
                        stripeMode === m
                          ? m === "live"
                            ? "border-emerald-500 bg-emerald-50"
                            : "border-amber-400 bg-amber-50"
                          : "border-neutral-200 hover:border-neutral-300"
                      }`}
                    >
                      <input
                        type="radio"
                        name="stripe_mode"
                        value={m}
                        checked={stripeMode === m}
                        onChange={() => setStripeMode(m)}
                        className="sr-only"
                      />
                      {m === "live"
                        ? <ShieldCheck size={20} className="shrink-0 text-emerald-600" />
                        : <AlertTriangle size={20} className="shrink-0 text-amber-500" />}
                      <div>
                        <div className={`text-sm font-bold ${stripeMode === m ? (m === "live" ? "text-emerald-700" : "text-amber-700") : "text-neutral-600"}`}>
                          {m === "live" ? "Live Mode" : "Sandbox / Test Mode"}
                        </div>
                        <div className="text-xs text-neutral-400 mt-0.5">
                          {m === "live" ? "Real payments processed. Use with care." : "No real charges. A banner will appear on all pages."}
                        </div>
                      </div>
                    </label>
                  ))}
                </div>
              </SectionCard>

              <SectionCard title="Live Keys" description="From your Stripe Dashboard → Developers → API keys (Live mode).">
                <div className="space-y-4">
                  <Field label="Secret Key (sk_live_…)">
                    <SecretInput name="stripe_live_secret_key" defaultValue={s["stripe_live_secret_key"]} placeholder="sk_live_…" />
                  </Field>
                  <Field label="Publishable Key (pk_live_…)">
                    <Input name="stripe_live_publishable_key" defaultValue={s["stripe_live_publishable_key"]} placeholder="pk_live_…" />
                  </Field>
                  <Field label="Webhook Signing Secret (whsec_…)" hint="From Stripe → Webhooks → your endpoint → Signing secret.">
                    <SecretInput name="stripe_live_webhook_secret" defaultValue={s["stripe_live_webhook_secret"]} placeholder="whsec_…" />
                  </Field>
                </div>
              </SectionCard>

              <SectionCard title="Sandbox / Test Keys" description="From Stripe Dashboard → Developers → API keys (Test mode).">
                <div className="space-y-4">
                  <Field label="Test Secret Key (sk_test_…)">
                    <SecretInput name="stripe_sandbox_secret_key" defaultValue={s["stripe_sandbox_secret_key"]} placeholder="sk_test_…" />
                  </Field>
                  <Field label="Test Publishable Key (pk_test_…)">
                    <Input name="stripe_sandbox_publishable_key" defaultValue={s["stripe_sandbox_publishable_key"]} placeholder="pk_test_…" />
                  </Field>
                  <Field label="Test Webhook Secret (whsec_…)">
                    <SecretInput name="stripe_sandbox_webhook_secret" defaultValue={s["stripe_sandbox_webhook_secret"]} placeholder="whsec_…" />
                  </Field>
                </div>
                <div className="mt-4 p-3 bg-neutral-50 rounded-lg border border-neutral-200 text-xs text-neutral-500">
                  <strong>Webhook URL:</strong>{" "}
                  <code className="font-mono">https://kc-systems.com/api/webhooks/stripe</code>
                  <br />
                  Required events: <code className="font-mono">checkout.session.completed · invoice.paid · customer.subscription.deleted · customer.subscription.updated</code>
                </div>
              </SectionCard>

              <div className="flex justify-end">
                <SaveButton pending={isPending} />
              </div>
            </form>
          )}

          {/* ── EMAIL ── */}
          {tab === "email" && (
            <form onSubmit={handle(saveEmailSettings, "Email settings saved.")} className="space-y-6">
              <SectionCard title="Mailgun Configuration" description="Transactional email delivery via Mailgun. API key is stored encrypted in the database.">
                <div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
                  <Field label="Mailgun Domain" hint="e.g. mg.yourdomain.com">
                    <Input name="mailgun_domain" defaultValue={s["mailgun_domain"]} placeholder="mg.kcsystems.com" />
                  </Field>
                  <Field label="Region">
                    <Select name="mailgun_region" defaultValue={s["mailgun_region"] || "us"}>
                      <option value="us">US (api.mailgun.net)</option>
                      <option value="eu">EU (api.eu.mailgun.net)</option>
                    </Select>
                  </Field>
                  <div className="sm:col-span-2">
                    <Field label="API Key" hint="Found in Mailgun → Settings → API keys.">
                      <SecretInput name="mailgun_api_key" defaultValue={s["mailgun_api_key"]} placeholder="key-…" />
                    </Field>
                  </div>
                </div>
              </SectionCard>

              <SectionCard title="Sender Details" description="How emails appear in recipients' inboxes.">
                <div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
                  <Field label="From Name" hint="Appears as the sender name.">
                    <Input name="mail_from_name" defaultValue={s["mail_from_name"]} placeholder="KC Systems" />
                  </Field>
                  <Field label="From Address" hint="Must be verified in Mailgun.">
                    <Input name="mail_from_address" type="email" defaultValue={s["mail_from_address"]} placeholder="noreply@kcsystems.com" />
                  </Field>
                  <Field label="Reply-To Address" hint="Where user replies will go. Optional.">
                    <Input name="mail_reply_to" type="email" defaultValue={s["mail_reply_to"]} placeholder="support@kcsystems.com" />
                  </Field>
                </div>
              </SectionCard>

              <div className="flex justify-end">
                <SaveButton pending={isPending} />
              </div>
            </form>
          )}

          {/* ── SOCIAL & CONTACT ── */}
          {tab === "social" && (
            <form onSubmit={handle(saveSocialSettings, "Social settings saved.")} className="space-y-6">
              <SectionCard title="WhatsApp" description="Floating WhatsApp button shown to visitors.">
                <div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
                  <Field label="WhatsApp Number" hint="Include country code, e.g. +60123456789">
                    <Input name="whatsapp_number" defaultValue={s["whatsapp_number"]} placeholder="+60123456789" />
                  </Field>
                  <Field label="Show Button">
                    <Select name="whatsapp_enabled" defaultValue={s["whatsapp_enabled"] || "true"}>
                      <option value="true">Enabled</option>
                      <option value="false">Disabled</option>
                    </Select>
                  </Field>
                </div>
              </SectionCard>

              <SectionCard title="Social Media Links" description="Used in the footer and profile pages. Leave blank to hide.">
                <div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
                  <Field label="Facebook">
                    <Input name="facebook_url" defaultValue={s["facebook_url"]} placeholder="https://facebook.com/…" />
                  </Field>
                  <Field label="Instagram">
                    <Input name="instagram_url" defaultValue={s["instagram_url"]} placeholder="https://instagram.com/…" />
                  </Field>
                  <Field label="Twitter / X">
                    <Input name="twitter_url" defaultValue={s["twitter_url"]} placeholder="https://x.com/…" />
                  </Field>
                  <Field label="LinkedIn">
                    <Input name="linkedin_url" defaultValue={s["linkedin_url"]} placeholder="https://linkedin.com/company/…" />
                  </Field>
                  <Field label="YouTube">
                    <Input name="youtube_url" defaultValue={s["youtube_url"]} placeholder="https://youtube.com/@…" />
                  </Field>
                </div>
              </SectionCard>

              <div className="flex justify-end">
                <SaveButton pending={isPending} />
              </div>
            </form>
          )}

          {/* ── ACCESS CONTROL ── */}
          {tab === "access" && (
            <form onSubmit={handle(saveTesterSettings, "Access settings saved.")} className="space-y-6">
              <SectionCard
                title="Coming Soon / Tester Gate"
                description="When enabled, all visitors see a Coming Soon page. A hidden 'tester' link at the bottom lets testers enter a password to access the full site."
              >
                <div className="space-y-5">
                  {/* Mode toggle */}
                  <div>
                    <label className="block text-xs font-semibold text-neutral-500 uppercase tracking-wide mb-3">Mode</label>
                    <div className="flex gap-3">
                      {([{ val: "false", label: "Off — site is public", desc: "All visitors see the full website." }, { val: "true", label: "On — Coming Soon active", desc: "Visitors see Coming Soon. Testers enter password to bypass." }] as const).map(({ val, label, desc }) => {
                        const active = testerMode === val;
                        return (
                          <label
                            key={val}
                            className={`flex-1 flex items-start gap-3 px-4 py-4 rounded-xl border-2 cursor-pointer transition-all ${
                              active
                                ? val === "false"
                                  ? "border-emerald-500 bg-emerald-50"
                                  : "border-amber-400 bg-amber-50"
                                : "border-neutral-200 hover:border-neutral-300"
                            }`}
                          >
                            <input type="radio" name="tester_mode" value={val} checked={testerMode === val} onChange={() => setTesterMode(val)} className="sr-only" />
                            <div className={`mt-0.5 w-4 h-4 rounded-full border-2 flex items-center justify-center shrink-0 ${active ? (val === "false" ? "border-emerald-500" : "border-amber-500") : "border-neutral-300"}`}>
                              {active && <div className={`w-2 h-2 rounded-full ${val === "false" ? "bg-emerald-500" : "bg-amber-500"}`} />}
                            </div>
                            <div>
                              <div className={`text-sm font-semibold ${active ? (val === "false" ? "text-emerald-700" : "text-amber-700") : "text-neutral-600"}`}>{label}</div>
                              <div className="text-xs text-neutral-400 mt-0.5">{desc}</div>
                            </div>
                          </label>
                        );
                      })}
                    </div>
                  </div>

                  {/* Password */}
                  <Field label="Tester Password" hint="Set a new password for testers to bypass the Coming Soon screen. Leave blank to keep the current password.">
                    <SecretInput name="tester_password" placeholder="Enter new tester password…" />
                  </Field>

                  {/* How it works */}
                  <div className="p-4 bg-neutral-50 rounded-xl border border-neutral-200 text-xs text-neutral-500 space-y-1.5">
                    <p className="font-semibold text-neutral-600 mb-2">How it works:</p>
                    <p>1. Turn On → all visitors see the Coming Soon page.</p>
                    <p>2. A tiny <span className="font-mono text-neutral-400">tester</span> label at the bottom of the page reveals a password prompt.</p>
                    <p>3. Enter the password → a secure cookie is set → full site is visible for 30 days.</p>
                    <p>4. To revoke access, change the password — existing tester cookies become invalid immediately.</p>
                    <p>5. Admin panel (<code className="font-mono">/admin</code>) and API routes are always accessible regardless of this setting.</p>
                  </div>
                </div>
              </SectionCard>

              <div className="flex justify-end">
                <SaveButton pending={isPending} />
              </div>
            </form>
          )}

        </main>
      </div>
    </div>
  );
}
