"use client";

import { FormEvent, useState } from "react";
import {
  Card,
  CardContent,
  CardDescription,
  CardHeader,
  CardTitle,
} from "@/components/ui/card";
import { Button } from "@/components/ui/button";
import { Badge } from "@/components/ui/badge";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogFooter,
  DialogHeader,
  DialogTitle,
} from "@/components/ui/dialog";
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from "@/components/ui/select";
import {
  Users,
  Search,
  Filter,
  Lock,
  Unlock,
  UserCheck,
  UserX,
  Trash2,
  ChevronLeft,
  ChevronRight,
  Eye,
  KeyRound,
} from "lucide-react";
import {
  useUsers,
  useLockUser,
  useUnlockUser,
  useDisableUser,
  useEnableUser,
  useDeleteUser,
  useUpdateUserPassword,
} from "@/hooks";
import { RoleEnums } from "@/types/api";
import { Avatar, AvatarFallback, AvatarImage } from "@/components/ui/avatar";
import { UserDetailsDialog } from "@/components/user-details-dialog";
import { toast } from "sonner";

export default function UsersPage() {
  const [currentPage, setCurrentPage] = useState(1);
  const [pageSize, setPageSize] = useState(10);
  const [searchTerm, setSearchTerm] = useState("");
  // const [roleFilter, setRoleFilter] = useState("");
  const [statusFilter, setStatusFilter] = useState("");
  const [sortBy, setSortBy] = useState("createdAt");
  const [sortOrder, setSortOrder] = useState<"asc" | "desc">("desc");
  const [selectedUserId, setSelectedUserId] = useState<string | null>(null);
  const [isUserDialogOpen, setIsUserDialogOpen] = useState(false);
  const [passwordUserId, setPasswordUserId] = useState<string | null>(null);
  const [isPasswordDialogOpen, setIsPasswordDialogOpen] = useState(false);
  const [newPassword, setNewPassword] = useState("");
  const [confirmPassword, setConfirmPassword] = useState("");

  // Fetch users with filters
  const { data: usersData, isLoading: usersLoading } = useUsers({
    page: currentPage,
    limit: pageSize,
    search: searchTerm || undefined,
    // role: roleFilter && roleFilter !== "all" ? roleFilter : undefined,
    status: statusFilter && statusFilter !== "all" ? statusFilter : undefined,
    sortBy,
    sortOrder,
  });

  // User management mutations
  const lockUserMutation = useLockUser();
  const unlockUserMutation = useUnlockUser();
  const disableUserMutation = useDisableUser();
  const enableUserMutation = useEnableUser();
  const deleteUserMutation = useDeleteUser();
  const updateUserPasswordMutation = useUpdateUserPassword();

  const getStatusColor = (status: string) => {
    switch (status) {
      case "active":
        return "bg-green-100 text-green-800 capitalize  ";
      case "locked":
        return "bg-yellow-100 text-yellow-800 capitalize";
      case "disabled":
        return "bg-red-100 text-red-800 capitalize";
      case "suspended":
        return "bg-orange-100 text-orange-800 capitalize";
      default:
        return "bg-gray-100 text-gray-800 capitalize";
    }
  };

  const getRoleColor = (role: string) => {
    switch (role) {
      case RoleEnums.SuperAdmin:
        return "bg-purple-100 text-purple-800 capitalize";
      case RoleEnums.Admin:
        return "bg-blue-100 text-blue-800 capitalize";
      case RoleEnums.Moderator:
        return "bg-green-100 text-green-800 capitalize";
      case RoleEnums.User:
        return "bg-gray-100 text-gray-800 capitalize";
      default:
        return "bg-gray-100 text-gray-800 capitalize";
    }
  };

  const handleChangePasswordUser = (userId: string) => {
    setPasswordUserId(userId);
    setIsPasswordDialogOpen(true);
  };

  const handleClosePasswordDialog = () => {
    setIsPasswordDialogOpen(false);
    setPasswordUserId(null);
    setNewPassword("");
    setConfirmPassword("");
  };

  const handleUpdatePassword = async (event: FormEvent<HTMLFormElement>) => {
    event.preventDefault();
    if (!passwordUserId) {
      toast.error("Unable to determine selected user.");
      return;
    }
    if (!newPassword.trim()) {
      toast.error("Password is required.");
      return;
    }
    if (newPassword !== confirmPassword) {
      toast.error("Passwords do not match.");
      return;
    }

    try {
      await updateUserPasswordMutation.mutateAsync({
        id: passwordUserId,
        passwordData: { password: newPassword },
      });
      handleClosePasswordDialog();
    } catch (error) {
      console.error("Failed to update password:", error);
    }
  };

  // User action handlers
  const handleLockUser = async (userId: string) => {
    try {
      await lockUserMutation.mutateAsync({
        id: userId,
        lockData: { reason: "Account locked by admin" },
      });
    } catch (error) {
      console.error("Failed to lock user:", error);
    }
  };

  const handleUnlockUser = async (userId: string) => {
    try {
      await unlockUserMutation.mutateAsync(userId);
    } catch (error) {
      console.error("Failed to unlock user:", error);
    }
  };

  const handleDisableUser = async (userId: string) => {
    try {
      await disableUserMutation.mutateAsync({
        id: userId,
        disableData: { reason: "Account disabled by admin" },
      });
    } catch (error) {
      console.error("Failed to disable user:", error);
    }
  };

  const handleEnableUser = async (userId: string) => {
    try {
      await enableUserMutation.mutateAsync(userId);
    } catch (error) {
      console.error("Failed to enable user:", error);
    }
  };

  const handleDeleteUser = async (userId: string) => {
    if (
      confirm(
        "Are you sure you want to delete this user? This action cannot be undone."
      )
    ) {
      try {
        await deleteUserMutation.mutateAsync({
          id: userId,
          deleteData: { reason: "User deleted by admin" },
        });
      } catch (error) {
        console.error("Failed to delete user:", error);
      }
    }
  };

  const handleViewProfile = (userId: string) => {
    setSelectedUserId(userId);
    setIsUserDialogOpen(true);
  };

  const handleCloseUserDialog = () => {
    setIsUserDialogOpen(false);
    setSelectedUserId(null);
  };

  const handleSearch = (value: string) => {
    setSearchTerm(value);
    setCurrentPage(1); // Reset to first page when searching
  };

  const handleFilterChange = (filterType: string, value: string) => {
    switch (filterType) {
      case "role":
        // setRoleFilter(value);
        break;
      case "status":
        setStatusFilter(value);
        break;
      case "sortBy":
        setSortBy(value);
        break;
      case "sortOrder":
        setSortOrder(value as "asc" | "desc");
        break;
    }
    setCurrentPage(1); // Reset to first page when filtering
  };

  const totalPages = Math.ceil((usersData?.data?.total || 0) / pageSize);

  return (
    <div className="flex-1 space-y-6 p-6">
      {/* Header */}
      <div className="flex items-center justify-between">
        <div>
          <h1 className="text-3xl font-bold tracking-tight">User Management</h1>
          <p className="text-muted-foreground">
            Manage platform users and their permissions
          </p>
        </div>
        {/* <Button>
          <Plus className="h-4 w-4 mr-2" />
          Add User
        </Button> */}
      </div>

      {/* Filters */}
      <Card>
        <CardHeader>
          <CardTitle className="flex items-center">
            <Filter className="h-5 w-5 mr-2" />
            Filters & Search
          </CardTitle>
        </CardHeader>
        <CardContent>
          <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-5 gap-4">
            {/* Search */}
            <div className="space-y-2">
              <Label htmlFor="search">Search</Label>
              <div className="relative">
                <Search className="absolute left-2 top-2.5 h-4 w-4 text-muted-foreground" />
                <Input
                  id="search"
                  placeholder="Search users..."
                  value={searchTerm}
                  onChange={(e) => handleSearch(e.target.value)}
                  className="pl-8"
                />
              </div>
            </div>

            {/* Role Filter */}
            {/* <div className="space-y-2">
              <Label htmlFor="role">Role</Label>
              <Select
                value={roleFilter}
                onValueChange={(value) => handleFilterChange("role", value)}
              >
                <SelectTrigger>
                  <SelectValue placeholder="All roles" />
                </SelectTrigger>
                <SelectContent>
                  <SelectItem value="all">All roles</SelectItem>
                  <SelectItem value={RoleEnums.User}>User</SelectItem>
                  <SelectItem value={RoleEnums.Moderator}>Moderator</SelectItem>
                  <SelectItem value={RoleEnums.Admin}>Admin</SelectItem>
                  <SelectItem value={RoleEnums.SuperAdmin}>Super Admin</SelectItem>
                </SelectContent>
              </Select>
            </div> */}

            {/* Status Filter */}
            <div className="space-y-2">
              <Label htmlFor="status">Status</Label>
              <Select
                value={statusFilter}
                onValueChange={(value) => handleFilterChange("status", value)}
              >
                <SelectTrigger>
                  <SelectValue placeholder="All statuses" />
                </SelectTrigger>
                <SelectContent>
                  <SelectItem value="all">All statuses</SelectItem>
                  <SelectItem value="active">Active</SelectItem>
                  <SelectItem value="locked">Locked</SelectItem>
                  <SelectItem value="disabled">Disabled</SelectItem>
                  <SelectItem value="suspended">Suspended</SelectItem>
                </SelectContent>
              </Select>
            </div>

            {/* Sort By */}
            <div className="space-y-2">
              <Label htmlFor="sortBy">Sort By</Label>
              <Select
                value={sortBy}
                onValueChange={(value) => handleFilterChange("sortBy", value)}
              >
                <SelectTrigger>
                  <SelectValue />
                </SelectTrigger>
                <SelectContent>
                  <SelectItem value="createdAt">Created Date</SelectItem>
                  <SelectItem value="fullName">Name</SelectItem>
                  <SelectItem value="email">Email</SelectItem>
                  <SelectItem value="role">Role</SelectItem>
                </SelectContent>
              </Select>
            </div>

            {/* Sort Order */}
            <div className="space-y-2">
              <Label htmlFor="sortOrder">Order</Label>
              <Select
                value={sortOrder}
                onValueChange={(value) =>
                  handleFilterChange("sortOrder", value)
                }
              >
                <SelectTrigger>
                  <SelectValue />
                </SelectTrigger>
                <SelectContent>
                  <SelectItem value="desc">Descending</SelectItem>
                  <SelectItem value="asc">Ascending</SelectItem>
                </SelectContent>
              </Select>
            </div>
          </div>
        </CardContent>
      </Card>

      {/* Users List */}
      <Card>
        <CardHeader>
          <CardTitle className="flex items-center">
            <Users className="h-5 w-5 mr-2" />
            Users ({usersData?.data?.total || 0})
          </CardTitle>
          <CardDescription>
            Showing {usersData?.data?.users?.length || 0} of{" "}
            {usersData?.data?.total || 0} users
          </CardDescription>
        </CardHeader>
        <CardContent>
          {usersLoading ? (
            <div className="space-y-3">
              {[...Array(5)].map((_, i) => (
                <div
                  key={i}
                  className="flex items-center justify-between p-3 border rounded-lg animate-pulse"
                >
                  <div className="flex items-center space-x-3">
                    <div className="h-10 w-10 bg-gray-200 rounded-full"></div>
                    <div className="space-y-2">
                      <div className="h-4 bg-gray-200 rounded w-32"></div>
                      <div className="h-3 bg-gray-200 rounded w-24"></div>
                    </div>
                  </div>
                  <div className="flex space-x-2">
                    <div className="h-8 w-16 bg-gray-200 rounded"></div>
                    <div className="h-8 w-16 bg-gray-200 rounded"></div>
                  </div>
                </div>
              ))}
            </div>
          ) : (
            <div className="space-y-3">
              {usersData?.data?.users?.map((user) => (
                <div
                  key={user._id}
                  className="flex items-center justify-between p-3 border rounded-lg"
                >
                  <div className="flex items-center space-x-3">
                    <Avatar>
                      <AvatarImage src={user.profile?.profilePicture?.url} />
                      <AvatarFallback>
                        {user?.fullName && user.fullName.length > 0
                          ? user.fullName.charAt(0).toUpperCase()
                          : "U"}
                      </AvatarFallback>
                    </Avatar>
                    <div>
                      <h4 className="font-medium">
                        {user.profile?.fullName ||
                          user?.fullName ||
                          user.email.split("@")[0]}
                      </h4>
                      <p className="text-sm text-muted-foreground">
                        {user.email}
                      </p>
                      <p className="text-xs text-muted-foreground">
                        Joined: {new Date(user.createdAt).toLocaleDateString()}
                      </p>
                    </div>
                  </div>
                  <div className="flex items-center space-x-2 ">
                    <Badge
                      className={`${getRoleColor(
                        user.role
                      )} hidden md:flex capitalize`}
                    >
                      {user.role}
                    </Badge>
                    <Badge
                      className={getStatusColor(
                        // user.isLocked
                        //   ? "locked"
                        // :
                        user.isDisabled ? "disabled" : "active"
                      )}
                    >
                      {
                        // user.isLocked
                        //   ? "Locked"
                        // :
                        user.isDisabled ? "Disabled" : "Active"
                      }
                    </Badge>
                    <Button
                      variant="outline"
                      size="sm"
                      title="View Profile"
                      onClick={() => handleViewProfile(user._id)}
                    >
                      <Eye className="h-4 w-4" />
                    </Button>
                    {/* {user.isLocked ? (
                      <Button
                        variant="outline"
                        size="sm"
                        className="hidden md:flex"
                        onClick={() => handleUnlockUser(user._id)}
                        disabled={unlockUserMutation.isPending}
                        title="Unlock User"
                      >
                        <Unlock className="h-4 w-4" />
                      </Button>
                    ) : (
                      <Button
                        variant="outline"
                        size="sm"
                        className="hidden md:flex"
                        onClick={() => handleLockUser(user._id)}
                        disabled={lockUserMutation.isPending}
                        title="Lock User"
                      >
                        <Lock className="h-4 w-4" />
                      </Button>
                    )} */}
                    <Button
                      variant="outline"
                      size="sm"
                      className="hidden md:flex"
                      onClick={() => handleChangePasswordUser(user._id)}
                      disabled={
                        updateUserPasswordMutation.isPending &&
                        passwordUserId === user._id
                      }
                      title="Change Password"
                    >
                      <KeyRound className="h-4 w-4" />
                    </Button>
                    {user.isDisabled ? (
                      <Button
                        variant="outline"
                        size="sm"
                        onClick={() => handleEnableUser(user._id)}
                        disabled={enableUserMutation.isPending}
                        title="Enable User"
                        className="hidden md:flex"
                      >
                        <UserCheck className="h-4 w-4" />
                      </Button>
                    ) : (
                      <Button
                        variant="outline"
                        size="sm"
                        onClick={() => handleDisableUser(user._id)}
                        disabled={disableUserMutation.isPending}
                        title="Disable User"
                        className="hidden md:flex"
                      >
                        <UserX className="h-4 w-4" />
                      </Button>
                    )}
                    <Button
                      variant="outline"
                      size="sm"
                      onClick={() => handleDeleteUser(user._id)}
                      disabled={deleteUserMutation.isPending}
                      title="Delete User"
                      className="hidden md:flex"
                    >
                      <Trash2 className="h-4 w-4" />
                    </Button>
                  </div>
                </div>
              ))}
            </div>
          )}
        </CardContent>
      </Card>

      {/* Pagination */}
      {totalPages > 1 && (
        <Card>
          <CardContent className="pt-6">
            <div className="flex items-center justify-between">
              <div className="flex items-center space-x-2">
                <Label htmlFor="pageSize">Items per page:</Label>
                <Select
                  value={pageSize.toString()}
                  onValueChange={(value) => {
                    setPageSize(parseInt(value));
                    setCurrentPage(1);
                  }}
                >
                  <SelectTrigger className="w-20">
                    <SelectValue />
                  </SelectTrigger>
                  <SelectContent>
                    <SelectItem value="5">5</SelectItem>
                    <SelectItem value="10">10</SelectItem>
                    <SelectItem value="20">20</SelectItem>
                    <SelectItem value="50">50</SelectItem>
                  </SelectContent>
                </Select>
              </div>
              <div className="flex items-center space-x-2">
                <Button
                  variant="outline"
                  size="sm"
                  onClick={() => setCurrentPage(currentPage - 1)}
                  disabled={currentPage === 1}
                >
                  <ChevronLeft className="h-4 w-4" />
                  Previous
                </Button>
                <span className="text-sm text-muted-foreground">
                  Page {currentPage} of {totalPages}
                </span>
                <Button
                  variant="outline"
                  size="sm"
                  onClick={() => setCurrentPage(currentPage + 1)}
                  disabled={currentPage === totalPages}
                >
                  Next
                  <ChevronRight className="h-4 w-4" />
                </Button>
              </div>
            </div>
          </CardContent>
        </Card>
      )}

      {/* Update Password Dialog */}
      <Dialog
        open={isPasswordDialogOpen}
        onOpenChange={(open) => {
          if (!open) {
            handleClosePasswordDialog();
          }
        }}
      >
        <DialogContent>
          <DialogHeader>
            <DialogTitle>Update Password</DialogTitle>
            <DialogDescription>
              Set a new password for the selected user. Make sure it meets your
              security requirements.
            </DialogDescription>
          </DialogHeader>
          <form onSubmit={handleUpdatePassword} className="space-y-4">
            <div className="space-y-2">
              <Label htmlFor="newPassword">New Password</Label>
              <Input
                id="newPassword"
                type="password"
                value={newPassword}
                onChange={(e) => setNewPassword(e.target.value)}
                placeholder="Enter new password"
                required
              />
            </div>
            <div className="space-y-2">
              <Label htmlFor="confirmPassword">Confirm Password</Label>
              <Input
                id="confirmPassword"
                type="password"
                value={confirmPassword}
                onChange={(e) => setConfirmPassword(e.target.value)}
                placeholder="Re-enter new password"
                required
              />
            </div>
            <DialogFooter>
              <Button
                type="button"
                variant="outline"
                onClick={handleClosePasswordDialog}
                disabled={updateUserPasswordMutation.isPending}
              >
                Cancel
              </Button>
              <Button
                type="submit"
                disabled={updateUserPasswordMutation.isPending}
              >
                {updateUserPasswordMutation.isPending
                  ? "Updating..."
                  : "Update Password"}
              </Button>
            </DialogFooter>
          </form>
        </DialogContent>
      </Dialog>

      {/* User Details Dialog */}
      <UserDetailsDialog
        userId={selectedUserId}
        isOpen={isUserDialogOpen}
        onClose={handleCloseUserDialog}
      />
    </div>
  );
}
