"use client";

import {
  Ban,
  Check,
  Loader2,
  LogOut,
  MoreHorizontal,
  Shield,
  Trash2,
} from "lucide-react";
import { useState } from "react";
import type { UserAction } from "../../hooks/use-admin-users";
import { Button } from "../ui/button";
import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogFooter,
  DialogHeader,
  DialogTitle,
} from "../ui/dialog";
import {
  DropdownMenu,
  DropdownMenuContent,
  DropdownMenuItem,
  DropdownMenuSeparator,
  DropdownMenuTrigger,
} from "../ui/dropdown-menu";
import { Input } from "../ui/input";
import { Label } from "../ui/label";

interface UserActionMenuProps {
  userId: string;
  status: "active" | "banned";
  role: string | string[];
  disabled: boolean;
  onUserAction: (
    action: UserAction,
    userId: string,
    data?: unknown
  ) => Promise<{ success: boolean }>;
}

export function UserActionMenu({
  userId,
  status,
  role,
  disabled,
  onUserAction,
}: UserActionMenuProps) {
  // Dialog states
  const [showMenu, setShowMenu] = useState(false);

  const [showRemoveDialog, setShowRemoveDialog] = useState(false);
  const [showRoleDialog, setShowRoleDialog] = useState(false);
  const [showRevokeDialog, setShowRevokeDialog] = useState(false);

  // Form states
  const [newRole, setNewRole] = useState(
    Array.isArray(role) ? role.join(", ") : role
  );

  // Action pending states
  const [isRoleActionPending, setIsRoleActionPending] = useState(false);
  const [isRevokeActionPending, setIsRevokeActionPending] = useState(false);
  const [isRemoveActionPending, setIsRemoveActionPending] = useState(false);

  // Handle role change
  const handleRoleChange = async () => {
    if (!newRole.trim()) {
      return;
    }

    setIsRoleActionPending(true);

    try {
      // Parse comma-separated roles
      const roleValue = newRole.includes(",")
        ? newRole
            .split(",")
            .map((r) => r.trim())
            .filter(Boolean)
        : newRole.trim();

      const result = await onUserAction("setRole", userId, { role: roleValue });
      if (result.success) {
        setShowRoleDialog(false);
      }
    } finally {
      setIsRoleActionPending(false);
    }
  };

  // Handle session revocation
  const handleRevokeSessions = async () => {
    setIsRevokeActionPending(true);

    try {
      const result = await onUserAction("revokeSessions", userId);
      if (result.success) {
        setShowRevokeDialog(false);
      }
    } finally {
      setIsRevokeActionPending(false);
    }
  };

  // Handle user removal
  const handleRemoveUser = async () => {
    setIsRemoveActionPending(true);

    try {
      const result = await onUserAction("remove", userId);
      if (result.success) {
        setShowRemoveDialog(false);
      }
    } finally {
      setIsRemoveActionPending(false);
    }
  };

  return (
    <>
      <DropdownMenu open={showMenu} onOpenChange={setShowMenu}>
        <DropdownMenuTrigger>
          <Button
            variant="ghost"
            size="icon"
            disabled={disabled}
            onClick={() => setShowMenu(true)}
          >
            <MoreHorizontal className="h-4 w-4" />
            <span className="sr-only">Open menu</span>
          </Button>
        </DropdownMenuTrigger>
        <DropdownMenuContent align="end">
          {status === "active" ? (
            <DropdownMenuItem
              onClick={() => onUserAction("ban", userId)}
              disabled={disabled}
            >
              <Ban className="h-4 w-4 mr-2" />
              Ban
            </DropdownMenuItem>
          ) : (
            <DropdownMenuItem
              onClick={() => onUserAction("unban", userId)}
              disabled={disabled}
            >
              <Check className="h-4 w-4 mr-2" />
              Unban
            </DropdownMenuItem>
          )}

          <DropdownMenuItem
            onClick={() => {
              setShowMenu(false);
              setShowRoleDialog(true);
            }}
            disabled={disabled}
          >
            <Shield className="h-4 w-4 mr-2" />
            Change Role
          </DropdownMenuItem>

          <DropdownMenuItem
            onClick={() => {
              setShowMenu(false);
              setShowRevokeDialog(true);
            }}
            disabled={disabled}
          >
            <LogOut className="h-4 w-4 mr-2" />
            Revoke Sessions
          </DropdownMenuItem>

          <DropdownMenuSeparator />

          <DropdownMenuItem
            onClick={() => {
              setShowMenu(false);
              setShowRemoveDialog(true);
            }}
            className="text-red-600"
            disabled={disabled}
          >
            <Trash2 className="h-4 w-4 mr-2" />
            Remove
          </DropdownMenuItem>
        </DropdownMenuContent>
      </DropdownMenu>

      <Dialog open={showRemoveDialog} onOpenChange={setShowRemoveDialog}>
        <DialogContent
          className="sm:max-w-[425px] "
          onOpenAutoFocus={(e) => e.preventDefault()}
        >
          <DialogHeader>
            <DialogTitle>Remove User</DialogTitle>
            <DialogDescription>
              Are you sure you want to remove this user? This action cannot be
              undone.
            </DialogDescription>
          </DialogHeader>
          <DialogFooter>
            <Button
              disabled={isRemoveActionPending}
              variant="outline"
              onClick={() =>
                !isRemoveActionPending && setShowRemoveDialog(false)
              }
            >
              Cancel
            </Button>
            <Button
              disabled={isRemoveActionPending}
              variant="destructive"
              onClick={handleRemoveUser}
            >
              {isRemoveActionPending ? (
                <>
                  <Loader2 className="mr-2 h-4 w-4 animate-spin" />
                  Removing...
                </>
              ) : (
                "Remove"
              )}
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>

      <Dialog open={showRoleDialog} onOpenChange={setShowRoleDialog}>
        <DialogContent
          className="sm:max-w-[425px]"
          onOpenAutoFocus={(e) => e.preventDefault()}
        >
          <DialogHeader>
            <DialogTitle>Change User Role</DialogTitle>
            <DialogDescription>
              Update the role for this user.
            </DialogDescription>
          </DialogHeader>
          <div className="grid gap-4 py-4">
            <div className="grid grid-cols-4 items-center gap-4">
              <Label htmlFor="role" className="text-right">
                Role
              </Label>
              <Input
                id="role"
                value={newRole}
                onChange={(e) => setNewRole(e.target.value)}
                className="col-span-3"
                placeholder="user, admin"
                disabled={isRoleActionPending}
              />
            </div>
          </div>
          <DialogFooter>
            <Button
              disabled={isRoleActionPending}
              variant="outline"
              onClick={() => !isRoleActionPending && setShowRoleDialog(false)}
            >
              Cancel
            </Button>
            <Button disabled={isRoleActionPending} onClick={handleRoleChange}>
              {isRoleActionPending ? (
                <>
                  <Loader2 className="mr-2 h-4 w-4 animate-spin" />
                  Saving...
                </>
              ) : (
                "Save"
              )}
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>

      <Dialog open={showRevokeDialog} onOpenChange={setShowRevokeDialog}>
        <DialogContent
          className="sm:max-w-[425px]"
          onOpenAutoFocus={(e) => e.preventDefault()}
        >
          <DialogHeader>
            <DialogTitle>Revoke User Sessions</DialogTitle>
            <DialogDescription>
              This will log the user out of all active sessions. Are you sure
              you want to continue?
            </DialogDescription>
          </DialogHeader>
          <DialogFooter>
            <Button
              disabled={isRevokeActionPending}
              variant="outline"
              onClick={() =>
                !isRevokeActionPending && setShowRevokeDialog(false)
              }
            >
              Cancel
            </Button>
            <Button
              disabled={isRevokeActionPending}
              variant="destructive"
              onClick={handleRevokeSessions}
            >
              {isRevokeActionPending ? (
                <>
                  <Loader2 className="mr-2 h-4 w-4 animate-spin" />
                  Revoking...
                </>
              ) : (
                "Revoke Sessions"
              )}
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>
    </>
  );
}
