"use client";

import { useEffect, useState } from "react";
import { SOCIAL_PLATFORMS, SocialPlatform } from "@/lib/social-platforms";
import { SocialIcon, socialLabel } from "@/components/social-icons";

type Settings = {
  notificationEmail: string;
  stripePublishableKey: string;
  stripeSecretKeyConfigured: boolean;
  stripeWebhookSecretConfigured: boolean;
  businessAddress: string;
  businessPhone: string;
  businessHours: string;
  businessLat: number | null;
  businessLng: number | null;
} & Record<`${SocialPlatform}Enabled`, boolean> &
  Record<`${SocialPlatform}Url`, string>;

const PLATFORM_PLACEHOLDERS: Record<SocialPlatform, string> = {
  instagram: "https://instagram.com/yourhandle",
  facebook: "https://facebook.com/yourpage",
  tiktok: "https://tiktok.com/@yourhandle",
  youtube: "https://youtube.com/@yourchannel",
};

export default function AdminSettingsPage() {
  const [settings, setSettings] = useState<Settings | null>(null);
  const [notificationEmail, setNotificationEmail] = useState("");
  const [stripePublishableKey, setStripePublishableKey] = useState("");
  const [stripeSecretKey, setStripeSecretKey] = useState("");
  const [stripeWebhookSecret, setStripeWebhookSecret] = useState("");
  const [businessAddress, setBusinessAddress] = useState("");
  const [businessPhone, setBusinessPhone] = useState("");
  const [businessHours, setBusinessHours] = useState("");
  const [social, setSocial] = useState<Record<SocialPlatform, { enabled: boolean; url: string }>>({
    instagram: { enabled: false, url: "" },
    facebook: { enabled: false, url: "" },
    tiktok: { enabled: false, url: "" },
    youtube: { enabled: false, url: "" },
  });
  const [saving, setSaving] = useState(false);
  const [message, setMessage] = useState<string | null>(null);

  function applySettings(data: Settings) {
    setSettings(data);
    setNotificationEmail(data.notificationEmail);
    setStripePublishableKey(data.stripePublishableKey);
    setBusinessAddress(data.businessAddress);
    setBusinessPhone(data.businessPhone);
    setBusinessHours(data.businessHours);
    setSocial({
      instagram: { enabled: data.instagramEnabled, url: data.instagramUrl },
      facebook: { enabled: data.facebookEnabled, url: data.facebookUrl },
      tiktok: { enabled: data.tiktokEnabled, url: data.tiktokUrl },
      youtube: { enabled: data.youtubeEnabled, url: data.youtubeUrl },
    });
  }

  useEffect(() => {
    fetch("/api/admin/settings")
      .then((res) => res.json())
      .then(applySettings);
  }, []);

  async function handleSubmit(e: React.FormEvent) {
    e.preventDefault();
    setSaving(true);
    setMessage(null);

    const res = await fetch("/api/admin/settings", {
      method: "PUT",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({
        notificationEmail,
        stripePublishableKey,
        stripeSecretKey: stripeSecretKey || undefined,
        stripeWebhookSecret: stripeWebhookSecret || undefined,
        businessAddress,
        businessPhone,
        businessHours,
        instagramEnabled: social.instagram.enabled,
        instagramUrl: social.instagram.url,
        facebookEnabled: social.facebook.enabled,
        facebookUrl: social.facebook.url,
        tiktokEnabled: social.tiktok.enabled,
        tiktokUrl: social.tiktok.url,
        youtubeEnabled: social.youtube.enabled,
        youtubeUrl: social.youtube.url,
      }),
    });

    if (res.ok) {
      setMessage("Settings saved.");
      setStripeSecretKey("");
      setStripeWebhookSecret("");
      const refreshed = await fetch("/api/admin/settings").then((r) => r.json());
      applySettings(refreshed);
    } else {
      setMessage("Could not save settings.");
    }
    setSaving(false);
  }

  if (!settings) {
    return <p className="text-sm text-ink/60">Loading&hellip;</p>;
  }

  return (
    <div className="max-w-xl">
      <h1 className="font-display text-3xl text-rosewood">Settings</h1>
      <p className="mt-2 text-sm text-ink/60">
        Manage your business info, Stripe API keys, and social links.
      </p>

      <form onSubmit={handleSubmit} className="mt-8 space-y-10">
        <div className="space-y-6">
          <h2 className="font-display text-xl text-rosewood">Business Info</h2>

          <div>
            <label className="text-xs uppercase tracking-wide-plus text-rose-dark">Address</label>
            <p className="mt-1 text-xs text-ink/50">
              Powers the map and &ldquo;Get Directions&rdquo; link on the Contact page.
            </p>
            <textarea
              value={businessAddress}
              onChange={(e) => setBusinessAddress(e.target.value)}
              placeholder="123 Main Street, Suite 4, Your City, ST 00000"
              rows={2}
              className="mt-2 w-full rounded-lg border border-blush-dark/60 px-4 py-2.5 text-sm"
            />
            {businessAddress.trim() &&
              businessAddress === settings.businessAddress &&
              (settings.businessLat != null && settings.businessLng != null ? (
                <a
                  href={`https://www.openstreetmap.org/?mlat=${settings.businessLat}&mlon=${settings.businessLng}#map=17/${settings.businessLat}/${settings.businessLng}`}
                  target="_blank"
                  rel="noopener noreferrer"
                  className="mt-2 inline-block text-xs text-rosewood underline underline-offset-4"
                >
                  Pin found &mdash; check it&apos;s in the right spot &#8599;
                </a>
              ) : (
                <p className="mt-2 text-xs text-red-600">
                  Couldn&apos;t pinpoint this address on a free map. Try adding more detail (city,
                  state) &mdash; the map on /contact will stay hidden until this resolves, but
                  &ldquo;Get Directions&rdquo; still works.
                </p>
              ))}
          </div>

          <div>
            <label className="text-xs uppercase tracking-wide-plus text-rose-dark">
              Contact Number
            </label>
            <input
              value={businessPhone}
              onChange={(e) => setBusinessPhone(e.target.value)}
              placeholder="(555) 123-4567"
              className="mt-2 w-full rounded-lg border border-blush-dark/60 px-4 py-2.5 text-sm"
            />
          </div>

          <div>
            <label className="text-xs uppercase tracking-wide-plus text-rose-dark">
              Operating Hours
            </label>
            <p className="mt-1 text-xs text-ink/50">One line per entry, e.g. &ldquo;Mon &ndash; Sat: 9:00am &ndash; 6:00pm&rdquo;.</p>
            <textarea
              value={businessHours}
              onChange={(e) => setBusinessHours(e.target.value)}
              placeholder={"Mon – Sat: 9:00am – 6:00pm\nSunday: Closed"}
              rows={3}
              className="mt-2 w-full rounded-lg border border-blush-dark/60 px-4 py-2.5 text-sm"
            />
          </div>
        </div>

        <div className="space-y-4">
          <div>
            <h2 className="font-display text-xl text-rosewood">Social Media</h2>
            <p className="mt-1 text-xs text-ink/50">
              Enable a platform and add your link to show it in the site footer and on the
              Contact page.
            </p>
          </div>

          {SOCIAL_PLATFORMS.map((platform) => (
            <div
              key={platform}
              className="flex items-center gap-4 rounded-xl border border-blush-dark/50 p-4"
            >
              <span className="flex h-9 w-9 shrink-0 items-center justify-center rounded-full bg-blush text-rosewood">
                <SocialIcon platform={platform} className="h-4 w-4" />
              </span>
              <div className="flex-1">
                <label className="flex items-center gap-2 text-sm font-medium text-ink">
                  <input
                    type="checkbox"
                    checked={social[platform].enabled}
                    onChange={(e) =>
                      setSocial((prev) => ({
                        ...prev,
                        [platform]: { ...prev[platform], enabled: e.target.checked },
                      }))
                    }
                  />
                  {socialLabel(platform)}
                </label>
                <input
                  value={social[platform].url}
                  onChange={(e) =>
                    setSocial((prev) => ({
                      ...prev,
                      [platform]: { ...prev[platform], url: e.target.value },
                    }))
                  }
                  placeholder={PLATFORM_PLACEHOLDERS[platform]}
                  className="mt-2 w-full rounded-lg border border-blush-dark/60 px-3 py-2 text-sm"
                />
              </div>
            </div>
          ))}
        </div>

        <div className="space-y-6">
          <h2 className="font-display text-xl text-rosewood">Stripe &amp; Notifications</h2>

          <div>
            <label className="text-xs uppercase tracking-wide-plus text-rose-dark">
              Notification Email
            </label>
            <p className="mt-1 text-xs text-ink/50">
              Booking confirmations are sent here (bcc) in addition to the customer.
            </p>
            <input
              type="email"
              value={notificationEmail}
              onChange={(e) => setNotificationEmail(e.target.value)}
              placeholder="you@salon.com"
              className="mt-2 w-full rounded-lg border border-blush-dark/60 px-4 py-2.5 text-sm"
            />
          </div>

          <div>
            <label className="text-xs uppercase tracking-wide-plus text-rose-dark">
              Stripe Publishable Key
            </label>
            <input
              value={stripePublishableKey}
              onChange={(e) => setStripePublishableKey(e.target.value)}
              placeholder="pk_live_..."
              className="mt-2 w-full rounded-lg border border-blush-dark/60 px-4 py-2.5 font-mono text-sm"
            />
          </div>

          <div>
            <label className="text-xs uppercase tracking-wide-plus text-rose-dark">
              Stripe Secret Key
            </label>
            <p className="mt-1 text-xs text-ink/50">
              {settings.stripeSecretKeyConfigured
                ? "A secret key is already saved. Enter a new one to replace it."
                : "No secret key saved yet."}
            </p>
            <input
              value={stripeSecretKey}
              onChange={(e) => setStripeSecretKey(e.target.value)}
              placeholder="sk_live_..."
              type="password"
              className="mt-2 w-full rounded-lg border border-blush-dark/60 px-4 py-2.5 font-mono text-sm"
            />
          </div>

          <div>
            <label className="text-xs uppercase tracking-wide-plus text-rose-dark">
              Stripe Webhook Signing Secret
            </label>
            <p className="mt-1 text-xs text-ink/50">
              {settings.stripeWebhookSecretConfigured
                ? "A webhook secret is already saved. Enter a new one to replace it."
                : "From your Stripe webhook endpoint (starts with whsec_)."}
            </p>
            <input
              value={stripeWebhookSecret}
              onChange={(e) => setStripeWebhookSecret(e.target.value)}
              placeholder="whsec_..."
              type="password"
              className="mt-2 w-full rounded-lg border border-blush-dark/60 px-4 py-2.5 font-mono text-sm"
            />
          </div>
        </div>

        {message && <p className="text-sm text-rosewood">{message}</p>}

        <button
          type="submit"
          disabled={saving}
          className="rounded-full bg-rosewood px-6 py-2.5 text-xs uppercase tracking-wide-plus text-cream transition hover:bg-rose-dark disabled:opacity-50"
        >
          {saving ? "Saving…" : "Save Settings"}
        </button>
      </form>
    </div>
  );
}
