"use client"

import { useState, useTransition } from "react"
import { useRouter } from "next/navigation"
import { toast } from "sonner"
import { Ban, ShieldCheck, UserCog, MailCheck, Trash2, Crown } from "lucide-react"
import {
  changeUserPlan,
  banUser,
  unbanUser,
  impersonateUser,
  markEmailVerified,
  deleteUser,
} from "@/app/actions/admin"
import { Select } from "@/components/ui/select"
import { ConfirmModal } from "@/components/ui/confirm-modal"
import { cn } from "@/lib/utils"

interface UserActionsProps {
  userId: string
  email: string
  currentPlan: string
  banned: boolean
  isSelf: boolean
}

const PLAN_OPTIONS = [
  { value: "starter", label: "Starter" },
  { value: "pro", label: "Pro" },
  { value: "landlord", label: "Landlord" },
  { value: "lifetime", label: "Lifetime" },
]

function errMessage(e: unknown) {
  return e instanceof Error ? e.message : "Something went wrong"
}

export function UserActions({ userId, email, currentPlan, banned, isSelf }: UserActionsProps) {
  const router = useRouter()
  const [isPending, startTransition] = useTransition()
  const [plan, setPlan] = useState(currentPlan)
  const [showBan, setShowBan] = useState(false)
  const [banReason, setBanReason] = useState("")
  const [showImpersonate, setShowImpersonate] = useState(false)
  const [showDelete, setShowDelete] = useState(false)

  // Run a server action inside a transition; toast on success/error, then refresh.
  function run(fn: () => Promise<unknown>, successMsg: string, after?: () => void) {
    startTransition(async () => {
      try {
        await fn()
        toast.success(successMsg)
        after?.()
        router.refresh()
      } catch (e) {
        toast.error(errMessage(e))
      }
    })
  }

  function onApplyPlan() {
    if (plan === currentPlan) {
      toast.message("Plan unchanged")
      return
    }
    run(() => changeUserPlan(userId, plan), "Plan updated")
  }

  function onBan() {
    run(() => banUser(userId, banReason.trim() || undefined), "User banned", () => {
      setShowBan(false)
      setBanReason("")
    })
  }

  function onUnban() {
    run(() => unbanUser(userId), "User unbanned")
  }

  function onImpersonate() {
    // impersonateUser redirects to /dashboard on success — no toast needed.
    startTransition(async () => {
      try {
        await impersonateUser(userId)
      } catch (e) {
        toast.error(errMessage(e))
        setShowImpersonate(false)
      }
    })
  }

  function onVerify() {
    run(() => markEmailVerified(userId), "Email marked as verified")
  }

  function onDelete() {
    // deleteUser redirects to /admin/users on success.
    startTransition(async () => {
      try {
        await deleteUser(userId)
      } catch (e) {
        toast.error(errMessage(e))
        setShowDelete(false)
      }
    })
  }

  const btnBase =
    "w-full inline-flex items-center justify-center gap-2 rounded-xl px-4 py-2.5 text-sm font-semibold transition disabled:cursor-not-allowed disabled:opacity-50"

  return (
    <div className="space-y-4">
      {/* Plan */}
      <div className="rounded-2xl border border-white/[0.06] bg-[#16161f] p-5">
        <div className="flex items-center gap-2 text-white">
          <Crown className="h-4 w-4 text-amber-400" />
          <h3 className="text-sm font-semibold">Change plan</h3>
        </div>
        <p className="mt-1 text-xs text-white/40">Override the user&apos;s subscription tier.</p>
        <div className="mt-4 space-y-3">
          <Select value={plan} onChange={setPlan} options={PLAN_OPTIONS} />
          <button
            onClick={onApplyPlan}
            disabled={isPending}
            className={cn(btnBase, "bg-indigo-600 text-white hover:bg-indigo-500")}
          >
            Apply
          </button>
        </div>
      </div>

      {/* Account actions */}
      <div className="rounded-2xl border border-white/[0.06] bg-[#16161f] p-5">
        <div className="flex items-center gap-2 text-white">
          <UserCog className="h-4 w-4 text-rose-400" />
          <h3 className="text-sm font-semibold">Account</h3>
        </div>
        <div className="mt-4 space-y-2.5">
          {/* Ban / Unban */}
          {banned ? (
            <button
              onClick={onUnban}
              disabled={isPending}
              className={cn(btnBase, "border border-emerald-500/30 bg-emerald-500/10 text-emerald-300 hover:bg-emerald-500/20")}
            >
              <ShieldCheck className="h-4 w-4" /> Unban user
            </button>
          ) : (
            <button
              onClick={() => setShowBan(true)}
              disabled={isPending || isSelf}
              title={isSelf ? "You cannot ban yourself" : undefined}
              className={cn(btnBase, "border border-amber-500/30 bg-amber-500/10 text-amber-300 hover:bg-amber-500/20")}
            >
              <Ban className="h-4 w-4" /> Ban user
            </button>
          )}

          {/* Impersonate */}
          <button
            onClick={() => setShowImpersonate(true)}
            disabled={isPending || isSelf}
            title={isSelf ? "You cannot impersonate yourself" : undefined}
            className={cn(btnBase, "border border-white/10 bg-white/[0.03] text-white/70 hover:bg-white/[0.06] hover:text-white")}
          >
            <UserCog className="h-4 w-4" /> Impersonate
          </button>

          {/* Verify email */}
          <button
            onClick={onVerify}
            disabled={isPending}
            className={cn(btnBase, "border border-white/10 bg-white/[0.03] text-white/70 hover:bg-white/[0.06] hover:text-white")}
          >
            <MailCheck className="h-4 w-4" /> Mark email verified
          </button>
        </div>
      </div>

      {/* Danger zone */}
      <div className="rounded-2xl border border-red-500/20 bg-red-500/[0.03] p-5">
        <div className="flex items-center gap-2 text-red-400">
          <Trash2 className="h-4 w-4" />
          <h3 className="text-sm font-semibold">Danger zone</h3>
        </div>
        <p className="mt-1 text-xs text-white/40">
          Permanently deletes the user and ALL their data. This cannot be undone.
        </p>
        <button
          onClick={() => setShowDelete(true)}
          disabled={isPending || isSelf}
          title={isSelf ? "You cannot delete yourself" : undefined}
          className={cn(btnBase, "mt-4 bg-red-600 text-white hover:bg-red-500")}
        >
          <Trash2 className="h-4 w-4" /> Delete user
        </button>
      </div>

      {/* Ban modal (with reason input) */}
      {showBan && (
        <div className="fixed inset-0 z-[300] flex items-center justify-center px-4">
          <div className="absolute inset-0 bg-black/60 backdrop-blur-sm" onClick={() => !isPending && setShowBan(false)} />
          <div className="relative w-full max-w-sm overflow-hidden rounded-2xl border border-white/[0.08] bg-[#16161f] p-6 shadow-2xl shadow-black/80">
            <div className="mx-auto mb-4 flex h-12 w-12 items-center justify-center rounded-2xl border border-amber-500/20 bg-amber-500/10 text-amber-400">
              <Ban className="h-6 w-6" />
            </div>
            <h2 className="text-center text-base font-bold text-white">Ban {email}?</h2>
            <p className="mt-2 text-center text-sm text-white/50">
              The user will be signed out and blocked from signing in until unbanned.
            </p>
            <div className="mt-4">
              <label className="mb-1.5 block text-xs font-medium text-white/40">Reason (optional)</label>
              <input
                value={banReason}
                onChange={(e) => setBanReason(e.target.value)}
                placeholder="Banned by admin"
                className="w-full rounded-xl border border-white/[0.08] bg-white/[0.03] px-3 py-2.5 text-sm text-white placeholder-white/25 outline-none transition focus:border-amber-500/50 focus:ring-1 focus:ring-amber-500/30"
              />
            </div>
            <div className="mt-6 flex gap-3">
              <button
                onClick={() => setShowBan(false)}
                disabled={isPending}
                className="flex-1 rounded-xl border border-white/10 py-2.5 text-sm font-medium text-white/50 transition hover:border-white/20 hover:text-white disabled:opacity-50"
              >
                Cancel
              </button>
              <button
                onClick={onBan}
                disabled={isPending}
                className="flex-1 rounded-xl bg-amber-600 py-2.5 text-sm font-semibold text-white transition hover:bg-amber-500 disabled:opacity-50"
              >
                {isPending ? "Banning…" : "Ban user"}
              </button>
            </div>
          </div>
        </div>
      )}

      {/* Impersonate confirm */}
      <ConfirmModal
        open={showImpersonate}
        variant="warning"
        title={`Impersonate ${email}?`}
        description="You will be signed in as this user and redirected to their dashboard. Your admin session can be restored from the impersonation banner."
        confirmLabel="Impersonate"
        loading={isPending}
        onConfirm={onImpersonate}
        onCancel={() => setShowImpersonate(false)}
      />

      {/* Delete confirm */}
      <ConfirmModal
        open={showDelete}
        variant="danger"
        title={`Delete ${email}?`}
        description="This permanently deletes the user and ALL their data — properties, units, tenants, leases, payments and more. This action cannot be undone."
        confirmLabel="Delete user"
        loading={isPending}
        onConfirm={onDelete}
        onCancel={() => setShowDelete(false)}
      />
    </div>
  )
}
