"use client";
import { useState, useEffect } from "react";
import { useRouter } from "next/navigation";
import { IUser } from "@/models/user";
import {
  Box,
  Typography,
  Button,
  TextField,
  MenuItem,
  Avatar,
  Chip,
  Paper,
  Table,
  TableBody,
  TableCell,
  TableContainer,
  TableHead,
  TableRow,
  Dialog,
  DialogTitle,
  DialogContent,
  DialogActions,
  IconButton,
  Snackbar,
  Alert,
  CircularProgress,
  useMediaQuery,
  Theme,
  Grid,
  Card,
  CardContent,
  Skeleton,
  Tooltip,
  Divider,
} from "@mui/material";
import {
  Search,
  ArrowBack,
  Close,
  AdminPanelSettings,
  Person,
  Edit,
  Groups,
  Security,
  People,
} from "@mui/icons-material";

const UserRoleManagement = () => {
  const router = useRouter();
  const isMobile = useMediaQuery((theme: Theme) =>
    theme.breakpoints.down("sm")
  );
  const isTablet = useMediaQuery((theme: Theme) =>
    theme.breakpoints.down("md")
  );

  const [users, setUsers] = useState<IUser[]>([]);
  const [selectedUser, setSelectedUser] = useState<IUser | null>(null);
  const [newRole, setNewRole] = useState<"admin" | "user">("user");
  const [loading, setLoading] = useState({
    page: true,
    action: false,
  });
  const [error, setError] = useState<string | null>(null);
  const [success, setSuccess] = useState<string | null>(null);
  const [searchTerm, setSearchTerm] = useState("");
  const [snackbarOpen, setSnackbarOpen] = useState(false);

  // Fetch all users
  useEffect(() => {
    const fetchUsers = async () => {
      try {
        setLoading((prev) => ({ ...prev, page: true }));
        const res = await fetch("/api/users/updateUserRole");
        const data = await res.json();

        if (!res.ok) throw new Error(data.message || "Failed to fetch users");

        setUsers(data.data);
      } catch (err) {
        if (err instanceof Error) {
          setError(err.message);
          if (err.message.includes("Unauthorized")) {
            router.push("/login");
          }
        } else {
          setError("An unknown error occurred");
        }
      } finally {
        setLoading((prev) => ({ ...prev, page: false }));
      }
    };
    fetchUsers();
  }, [router]);

  // Filter users based on search term
  const filteredUsers = users.filter(
    (user) =>
      user.name?.toLowerCase().includes(searchTerm.toLowerCase()) ||
      user.email?.toLowerCase().includes(searchTerm.toLowerCase()) ||
      user.username?.toLowerCase().includes(searchTerm.toLowerCase())
  );

  const handleRoleUpdate = async () => {
    if (!selectedUser) return;

    setLoading((prev) => ({ ...prev, action: true }));
    setError(null);
    setSuccess(null);

    try {
      const res = await fetch(`/api/users/updateUserRole`, {
        method: "POST",
        headers: {
          "Content-Type": "application/json",
        },
        body: JSON.stringify({
          userId: selectedUser._id,
          newRole,
        }),
      });

      const data = await res.json();

      if (!res.ok) throw new Error(data.message || "Failed to update role");

      // Update local state
      setUsers(
        users.map((user) =>
          user._id === selectedUser._id
            ? ({ ...user, role: newRole } as IUser)
            : user
        )
      );

      setSuccess(
        `Successfully updated ${selectedUser.name}'s role to ${newRole}`
      );
      setSnackbarOpen(true);
      setSelectedUser(null);
    } catch (err) {
      setError(
        err instanceof Error ? err.message : "An unknown error occurred"
      );
      setSnackbarOpen(true);
    } finally {
      setLoading((prev) => ({ ...prev, action: false }));
    }
  };

  const handleCloseSnackbar = () => {
    setSnackbarOpen(false);
    setError(null);
    setSuccess(null);
  };

  return (
    <Box sx={{ p: isMobile ? 2 : 3, maxWidth: "1800px", margin: "0 auto" }}>
      {/* Header */}
      <Box
        sx={{
          display: "flex",
          flexDirection: isMobile ? "column" : "row",
          justifyContent: "space-between",
          alignItems: isMobile ? "flex-start" : "center",
          mb: 4,
          gap: isMobile ? 2 : 0,
        }}
      >
        <Typography variant="h4" component="h1" sx={{ fontWeight: 700 }}>
          User Role Management
        </Typography>
        <Button
          startIcon={<ArrowBack />}
          onClick={() => router.back()}
          variant="outlined"
          size={isMobile ? "small" : "medium"}
          sx={{ alignSelf: isMobile ? "flex-start" : "center" }}
        >
          Back
        </Button>
      </Box>

      {/* Search and Stats */}
      <Paper sx={{ p: 3, mb: 4, borderRadius: 2 }}>
        <TextField
          fullWidth
          variant="outlined"
          placeholder="Search users by name, email or username..."
          InputProps={{
            startAdornment: <Search sx={{ mr: 1, color: "text.secondary" }} />,
          }}
          value={searchTerm}
          onChange={(e) => setSearchTerm(e.target.value)}
          sx={{ mb: 3 }}
        />

        <Grid container spacing={3}>
          <Grid size={{ xs: 12, sm: 6, md: 4 }}>
            <Card
              sx={{
                bgcolor: "primary.light",
                color: "primary.contrastText",
                height: "100%",
              }}
            >
              <CardContent>
                <Box sx={{ display: "flex", alignItems: "center", mb: 1 }}>
                  <Groups sx={{ mr: 1.5 }} />
                  <Typography variant="subtitle1">Total Users</Typography>
                </Box>
                <Typography variant="h3">
                  {loading.page ? <Skeleton width="60%" /> : users.length}
                </Typography>
              </CardContent>
            </Card>
          </Grid>
          <Grid size={{ xs: 12, sm: 6, md: 4 }}>
            <Card
              sx={{
                bgcolor: "secondary.light",
                color: "secondary.contrastText",
                height: "100%",
              }}
            >
              <CardContent>
                <Box sx={{ display: "flex", alignItems: "center", mb: 1 }}>
                  <Security sx={{ mr: 1.5 }} />
                  <Typography variant="subtitle1">Administrators</Typography>
                </Box>
                <Typography variant="h3">
                  {loading.page ? (
                    <Skeleton width="60%" />
                  ) : (
                    users.filter((u) => u.role === "admin").length
                  )}
                </Typography>
              </CardContent>
            </Card>
          </Grid>
          <Grid size={{ xs: 12, sm: 6, md: 4 }}>
            <Card
              sx={{
                bgcolor: "success.light",
                color: "success.contrastText",
                height: "100%",
              }}
            >
              <CardContent>
                <Box sx={{ display: "flex", alignItems: "center", mb: 1 }}>
                  <People sx={{ mr: 1.5 }} />
                  <Typography variant="subtitle1">Regular Users</Typography>
                </Box>
                <Typography variant="h3">
                  {loading.page ? (
                    <Skeleton width="60%" />
                  ) : (
                    users.filter((u) => u.role === "user").length
                  )}
                </Typography>
              </CardContent>
            </Card>
          </Grid>
        </Grid>
      </Paper>

      {/* Users Table */}
      <Paper sx={{ borderRadius: 2, overflow: "hidden", boxShadow: 3 }}>
        {loading.page ? (
          <Box sx={{ p: 4, display: "flex", justifyContent: "center" }}>
            <CircularProgress size={60} />
          </Box>
        ) : (
          <TableContainer>
            <Table>
              <TableHead sx={{ bgcolor: "background.paper" }}>
                <TableRow>
                  <TableCell sx={{ fontWeight: 700, fontSize: "1rem" }}>
                    User
                  </TableCell>
                  {!isMobile && (
                    <TableCell sx={{ fontWeight: 700, fontSize: "1rem" }}>
                      Email
                    </TableCell>
                  )}
                  <TableCell sx={{ fontWeight: 700, fontSize: "1rem" }}>
                    Role
                  </TableCell>
                  <TableCell
                    sx={{ fontWeight: 700, fontSize: "1rem" }}
                    align="right"
                  >
                    Actions
                  </TableCell>
                </TableRow>
              </TableHead>
              <TableBody>
                {filteredUsers.length === 0 ? (
                  <TableRow>
                    <TableCell colSpan={4} sx={{ textAlign: "center", py: 6 }}>
                      <Box
                        sx={{
                          display: "flex",
                          flexDirection: "column",
                          alignItems: "center",
                        }}
                      >
                        <Search
                          sx={{ fontSize: 60, color: "text.disabled", mb: 2 }}
                        />
                        <Typography variant="h6" color="text.secondary">
                          No users found
                        </Typography>
                        <Typography
                          variant="body2"
                          color="text.secondary"
                          sx={{ mt: 1 }}
                        >
                          Try adjusting your search query
                        </Typography>
                      </Box>
                    </TableCell>
                  </TableRow>
                ) : (
                  filteredUsers.map((user) => (
                    <TableRow key={String(user._id)} hover>
                      <TableCell>
                        <Box
                          sx={{ display: "flex", alignItems: "center", gap: 2 }}
                        >
                          <Avatar
                            src={user.image || "/default-avatar.png"}
                            alt={user.name}
                            sx={{ width: 40, height: 40 }}
                          />
                          <Box>
                            <Typography variant="body1" fontWeight={500}>
                              {user.name || user.username}
                            </Typography>
                            {!isMobile && (
                              <Typography
                                variant="body2"
                                color="text.secondary"
                              >
                                @{user.username}
                              </Typography>
                            )}
                          </Box>
                        </Box>
                      </TableCell>
                      {!isMobile && (
                        <TableCell>
                          <Typography variant="body2">{user.email}</Typography>
                        </TableCell>
                      )}
                      <TableCell>
                        <Chip
                          label={
                            user.role === "admin" ? "Administrator" : "User"
                          }
                          icon={
                            user.role === "admin" ? (
                              <AdminPanelSettings fontSize="small" />
                            ) : (
                              <Person fontSize="small" />
                            )
                          }
                          color={user.role === "admin" ? "primary" : "default"}
                          size="small"
                          sx={{ textTransform: "capitalize" }}
                        />
                      </TableCell>
                      <TableCell align="right">
                        <Tooltip title="Edit role">
                          <IconButton
                            onClick={() => {
                              setSelectedUser(user);
                              setNewRole(user.role);
                            }}
                            color="primary"
                            size={isMobile ? "small" : "medium"}
                          >
                            <Edit fontSize={isMobile ? "small" : "medium"} />
                          </IconButton>
                        </Tooltip>
                      </TableCell>
                    </TableRow>
                  ))
                )}
              </TableBody>
            </Table>
          </TableContainer>
        )}
      </Paper>

      {/* Role Update Dialog */}
      <Dialog
        open={Boolean(selectedUser)}
        onClose={() => !loading.action && setSelectedUser(null)}
        fullWidth
        maxWidth="sm"
        PaperProps={{ sx: { borderRadius: 2 } }}
      >
        <DialogTitle
          sx={{
            bgcolor: "background.paper",
            borderBottom: 1,
            borderColor: "divider",
          }}
        >
          <Box
            sx={{
              display: "flex",
              justifyContent: "space-between",
              alignItems: "center",
            }}
          >
            <Typography variant="h6" fontWeight={600}>
              Update User Role
            </Typography>
            <IconButton
              onClick={() => !loading.action && setSelectedUser(null)}
              disabled={loading.action}
            >
              <Close />
            </IconButton>
          </Box>
        </DialogTitle>
        <DialogContent sx={{ p: 3 }}>
          {selectedUser && (
            <>
              <Box sx={{ mb: 3 }}>
                <Typography
                  variant="subtitle2"
                  color="text.secondary"
                  gutterBottom
                >
                  Updating role for:
                </Typography>
                <Box
                  sx={{
                    display: "flex",
                    alignItems: "center",
                    gap: 2,
                    p: 2,
                    bgcolor: "action.hover",
                    borderRadius: 1,
                  }}
                >
                  <Avatar
                    src={selectedUser.image || "/default-avatar.png"}
                    alt={selectedUser.name}
                    sx={{ width: 56, height: 56 }}
                  />
                  <Box>
                    <Typography variant="body1" fontWeight={500}>
                      {selectedUser.name || selectedUser.username}
                    </Typography>
                    <Typography variant="body2" color="text.secondary">
                      {selectedUser.email}
                    </Typography>
                    <Chip
                      label={`Current role: ${selectedUser.role}`}
                      size="small"
                      sx={{ mt: 1, textTransform: "capitalize" }}
                    />
                  </Box>
                </Box>
              </Box>

              <Divider sx={{ my: 2 }} />

              <TextField
                select
                fullWidth
                label="Select New Role"
                value={newRole}
                onChange={(e) => setNewRole(e.target.value as "admin" | "user")}
                disabled={loading.action}
                variant="outlined"
                size="medium"
              >
                <MenuItem value="user">
                  <Box sx={{ display: "flex", alignItems: "center", gap: 1 }}>
                    <Person /> Regular User
                  </Box>
                </MenuItem>
                <MenuItem value="admin">
                  <Box sx={{ display: "flex", alignItems: "center", gap: 1 }}>
                    <AdminPanelSettings /> Administrator
                  </Box>
                </MenuItem>
              </TextField>
            </>
          )}
        </DialogContent>
        <DialogActions sx={{ p: 3, borderTop: 1, borderColor: "divider" }}>
          <Button
            onClick={() => setSelectedUser(null)}
            disabled={loading.action}
            color="inherit"
            variant="outlined"
            size="large"
          >
            Cancel
          </Button>
          <Button
            onClick={handleRoleUpdate}
            disabled={loading.action || newRole === selectedUser?.role}
            color="primary"
            variant="contained"
            size="large"
            startIcon={
              loading.action ? (
                <CircularProgress size={20} color="inherit" />
              ) : null
            }
          >
            {loading.action ? "Updating..." : "Update Role"}
          </Button>
        </DialogActions>
      </Dialog>

      {/* Snackbar for notifications */}
      <Snackbar
        open={snackbarOpen}
        autoHideDuration={6000}
        onClose={handleCloseSnackbar}
        anchorOrigin={{ vertical: "top", horizontal: "right" }}
      >
        <Alert
          onClose={handleCloseSnackbar}
          severity={error ? "error" : "success"}
          sx={{ width: "100%", alignItems: "center" }}
          variant="filled"
        >
          <Typography variant="body1">{error || success}</Typography>
        </Alert>
      </Snackbar>
    </Box>
  );
};

export default UserRoleManagement;
