"use client"

import { useState, useTransition } from "react"
import * as Switch from "@radix-ui/react-switch"
import { toast } from "sonner"
import { Power } from "lucide-react"
import { setSiteMaintenance } from "@/app/actions/admin"

export function MaintenanceToggle({
  initialEnabled,
  initialMessage,
}: {
  initialEnabled: boolean
  initialMessage: string
}) {
  const [enabled, setEnabled] = useState(initialEnabled)
  const [message, setMessage] = useState(initialMessage)
  const [pending, startTransition] = useTransition()

  function persist(nextEnabled: boolean, nextMessage: string) {
    startTransition(async () => {
      try {
        await setSiteMaintenance(nextEnabled, nextMessage)
        toast.success(
          nextEnabled
            ? "Maintenance mode ON — the site is offline for everyone except admins."
            : "Maintenance mode OFF — the site is live."
        )
      } catch {
        setEnabled(!nextEnabled) // revert optimistic toggle
        toast.error("Couldn't update maintenance mode. Try again.")
      }
    })
  }

  function onToggle(next: boolean) {
    setEnabled(next)
    persist(next, message)
  }

  return (
    <div className="rounded-2xl border border-white/[0.06] bg-[#16161f] overflow-hidden">
      <div className="flex items-center gap-2 border-b border-white/[0.06] px-5 py-4">
        <Power className="h-4 w-4 text-rose-400 shrink-0" />
        <h2 className="text-sm font-semibold text-white">Maintenance mode</h2>
      </div>

      <div className="px-5 py-4 space-y-4">
        <div className="flex items-center justify-between gap-4">
          <div>
            <p className="text-sm text-white/80">
              {enabled ? "Site is offline" : "Site is live"}
            </p>
            <p className="mt-0.5 text-xs text-white/40">
              When on, all visitors see a maintenance page. Admins keep full access.
            </p>
          </div>

          <Switch.Root
            checked={enabled}
            onCheckedChange={onToggle}
            disabled={pending}
            aria-label="Toggle maintenance mode"
            className="relative h-6 w-11 shrink-0 cursor-pointer rounded-full bg-white/10 outline-none transition-colors data-[state=checked]:bg-rose-500 disabled:opacity-50 disabled:cursor-not-allowed"
          >
            <Switch.Thumb className="block h-5 w-5 translate-x-0.5 rounded-full bg-white shadow transition-transform will-change-transform data-[state=checked]:translate-x-[22px]" />
          </Switch.Root>
        </div>

        <div>
          <label htmlFor="maintenance-message" className="mb-1.5 block text-xs font-medium text-white/50">
            Message shown to visitors (optional)
          </label>
          <textarea
            id="maintenance-message"
            value={message}
            onChange={(e) => setMessage(e.target.value)}
            rows={2}
            placeholder="We're upgrading the platform and will be back shortly."
            className="w-full resize-none rounded-lg border border-white/10 bg-white/5 px-3 py-2 text-sm text-white placeholder-white/25 outline-none transition focus:border-rose-500/50 focus:ring-1 focus:ring-rose-500/30"
          />
          <div className="mt-2 flex justify-end">
            <button
              type="button"
              onClick={() => persist(enabled, message)}
              disabled={pending}
              className="rounded-lg border border-white/10 bg-white/5 px-3 py-1.5 text-xs font-medium text-white/80 transition hover:bg-white/10 disabled:opacity-50 disabled:cursor-not-allowed"
            >
              Save message
            </button>
          </div>
        </div>
      </div>
    </div>
  )
}
