"use client";
import { useState, useEffect } from "react";
import UserCard from "./userCard";
import { IUser } from "@/models/user";
import {
  Box,
  Grid,
  TextField,
  MenuItem,
  Select,
  Typography,
  Button,
  CircularProgress,
  Paper,
  Dialog,
  DialogTitle,
  DialogContent,
  DialogActions,
  IconButton,
  Avatar,
  Chip,
  useMediaQuery,
  useTheme,
  Card,
  CardContent,
  Divider,
  Tooltip,
  Skeleton,
  InputAdornment,
  Badge,
} from "@mui/material";
import {
  Close,
  FilterList,
  Search,
  Person,
  Event,
  Login,
  AccountBalanceWallet,
  ClearAll,
  VerifiedUser,
  Phone,
  Email,
  CalendarToday,
  Schedule,
  AccountCircle,
  Star,
} from "@mui/icons-material";
import { format } from "date-fns";

const UsersPage = () => {
  const theme = useTheme();
  const isMobile = useMediaQuery(theme.breakpoints.down("sm"));
  const isTablet = useMediaQuery(theme.breakpoints.down("md"));

  const [users, setUsers] = useState<IUser[]>([]);
  const [filteredUsers, setFilteredUsers] = useState<IUser[]>([]);
  const [selectedUser, setSelectedUser] = useState<IUser | null>(null);
  const [loading, setLoading] = useState(true);
  const [filtersOpen, setFiltersOpen] = useState(false);

  // Filter states
  const [dateJoinedFilter, setDateJoinedFilter] = useState<string>("all");
  const [lastLoginFilter, setLastLoginFilter] = useState<string>("all");
  const [balanceFilter, setBalanceFilter] = useState<string>("all");
  const [searchQuery, setSearchQuery] = useState<string>("");

  useEffect(() => {
    const fetchUsers = async () => {
      try {
        setLoading(true);
        const res = await fetch("/api/users/getUsers", {
          headers: {
            "Cache-Control": "no-cache, no-store",
          },
        });
        const data = await res.json();
        setUsers(data.data);
        setFilteredUsers(data.data);
      } catch (error) {
        console.error("Failed to fetch users:", error);
      } finally {
        setLoading(false);
      }
    };
    fetchUsers();
  }, []);

  useEffect(() => {
    applyFilters();
  }, [dateJoinedFilter, lastLoginFilter, balanceFilter, searchQuery, users]);

  const applyFilters = () => {
    let result = [...users];

    // Apply date joined filter
    if (dateJoinedFilter !== "all") {
      const now = new Date();
      const cutoffDate = new Date();

      if (dateJoinedFilter === "today") {
        cutoffDate.setDate(now.getDate() - 1);
      } else if (dateJoinedFilter === "week") {
        cutoffDate.setDate(now.getDate() - 7);
      } else if (dateJoinedFilter === "month") {
        cutoffDate.setMonth(now.getMonth() - 1);
      } else if (dateJoinedFilter === "year") {
        cutoffDate.setFullYear(now.getFullYear() - 1);
      }

      result = result.filter((user) => new Date(user.dateJoined) >= cutoffDate);
    }

    // Apply last login filter
    if (lastLoginFilter !== "all") {
      const now = new Date();
      const cutoffDate = new Date();

      if (lastLoginFilter === "today") {
        cutoffDate.setDate(now.getDate() - 1);
        result = result.filter(
          (user) => user.lastLogin && new Date(user.lastLogin) >= cutoffDate
        );
      } else if (lastLoginFilter === "week") {
        cutoffDate.setDate(now.getDate() - 7);
        result = result.filter(
          (user) => user.lastLogin && new Date(user.lastLogin) >= cutoffDate
        );
      } else if (lastLoginFilter === "month") {
        cutoffDate.setMonth(now.getMonth() - 1);
        result = result.filter(
          (user) => user.lastLogin && new Date(user.lastLogin) >= cutoffDate
        );
      } else if (lastLoginFilter === "never") {
        result = result.filter((user) => !user.lastLogin);
      }
    }

    // Apply balance filter
    if (balanceFilter !== "all") {
      if (balanceFilter === "zero") {
        result = result.filter((user) => user.accountBalance === 0);
      } else if (balanceFilter === "low") {
        result = result.filter(
          (user) => user.accountBalance > 0 && user.accountBalance <= 1000
        );
      } else if (balanceFilter === "medium") {
        result = result.filter(
          (user) => user.accountBalance > 1000 && user.accountBalance <= 10000
        );
      } else if (balanceFilter === "high") {
        result = result.filter((user) => user.accountBalance > 10000);
      }
    }

    // Apply search filter
    if (searchQuery) {
      const query = searchQuery.toLowerCase();
      result = result.filter(
        (user) =>
          user.name?.toLowerCase().includes(query) ||
          user.username?.toLowerCase().includes(query) ||
          user.email?.toLowerCase().includes(query) ||
          user.mobileNumber?.toLowerCase().includes(query)
      );
    }

    setFilteredUsers(result);
  };

  const handleViewProfile = (userId: string) => {
    const user = users.find((u) => u._id === userId);
    setSelectedUser(user || null);
  };

  const handleDeleteUser = async (userId: string) => {
    try {
      const res = await fetch(`/api/users/deleteuser?id=${userId}`, {
        method: "DELETE",
      });
      if (res.ok) {
        setUsers(users.filter((user) => user._id !== userId));
      }
    } catch (error) {
      console.error("Failed to delete user:", error);
    }
  };

  const clearFilters = () => {
    setDateJoinedFilter("all");
    setLastLoginFilter("all");
    setBalanceFilter("all");
    setSearchQuery("");
  };

  if (loading) {
    return (
      <Box
        display="flex"
        justifyContent="center"
        alignItems="center"
        minHeight="60vh"
      >
        <CircularProgress size={60} />
      </Box>
    );
  }

  return (
    <Box sx={{ p: isMobile ? 2 : 3, maxWidth: "1800px", mx: "auto" }}>
      {/* Header and Search */}
      <Box sx={{ mb: 4 }}>
        <Typography variant="h4" component="h1" sx={{ fontWeight: 700, mb: 2 }}>
          User Management
        </Typography>

        <Card sx={{ mb: 3, borderRadius: 2 }}>
          <CardContent sx={{ p: "16px !important" }}>
            <TextField
              fullWidth
              variant="outlined"
              placeholder="Search users by name, email, or phone..."
              value={searchQuery}
              onChange={(e) => setSearchQuery(e.target.value)}
              InputProps={{
                startAdornment: (
                  <InputAdornment position="start">
                    <Search color="action" />
                  </InputAdornment>
                ),
                endAdornment: (
                  <InputAdornment position="end">
                    <Tooltip title="Filter users">
                      <IconButton
                        onClick={() => setFiltersOpen(!filtersOpen)}
                        color={filtersOpen ? "primary" : "default"}
                      >
                        <Badge
                          color="primary"
                          variant="dot"
                          invisible={
                            dateJoinedFilter === "all" &&
                            lastLoginFilter === "all" &&
                            balanceFilter === "all"
                          }
                        >
                          <FilterList />
                        </Badge>
                      </IconButton>
                    </Tooltip>
                  </InputAdornment>
                ),
              }}
            />
          </CardContent>
        </Card>

        {/* Filters Panel */}
        {filtersOpen && (
          <Card sx={{ mb: 3, borderRadius: 2 }}>
            <CardContent>
              <Grid container spacing={2}>
                <Grid size={{ xs: 12, sm: 6, md: 4, lg: 3 }}>
                  <Typography
                    variant="subtitle2"
                    gutterBottom
                    sx={{ display: "flex", alignItems: "center", gap: 1 }}
                  >
                    <Event fontSize="small" /> Date Joined
                  </Typography>
                  <Select
                    fullWidth
                    size="small"
                    value={dateJoinedFilter}
                    onChange={(e) => setDateJoinedFilter(e.target.value)}
                  >
                    <MenuItem value="all">All Time</MenuItem>
                    <MenuItem value="today">Today</MenuItem>
                    <MenuItem value="week">Last 7 Days</MenuItem>
                    <MenuItem value="month">Last 30 Days</MenuItem>
                    <MenuItem value="year">Last Year</MenuItem>
                  </Select>
                </Grid>

                <Grid size={{ xs: 12, sm: 6, md: 4, lg: 3 }}>
                  <Typography
                    variant="subtitle2"
                    gutterBottom
                    sx={{ display: "flex", alignItems: "center", gap: 1 }}
                  >
                    <Login fontSize="small" /> Last Login
                  </Typography>
                  <Select
                    fullWidth
                    size="small"
                    value={lastLoginFilter}
                    onChange={(e) => setLastLoginFilter(e.target.value)}
                  >
                    <MenuItem value="all">Any Time</MenuItem>
                    <MenuItem value="today">Today</MenuItem>
                    <MenuItem value="week">Last 7 Days</MenuItem>
                    <MenuItem value="month">Last 30 Days</MenuItem>
                    <MenuItem value="never">Never</MenuItem>
                  </Select>
                </Grid>

                <Grid size={{ xs: 12, sm: 6, md: 4, lg: 3 }}>
                  <Typography
                    variant="subtitle2"
                    gutterBottom
                    sx={{ display: "flex", alignItems: "center", gap: 1 }}
                  >
                    <AccountBalanceWallet fontSize="small" /> Wallet Balance
                  </Typography>
                  <Select
                    fullWidth
                    size="small"
                    value={balanceFilter}
                    onChange={(e) => setBalanceFilter(e.target.value)}
                  >
                    <MenuItem value="all">All Balances</MenuItem>
                    <MenuItem value="zero">₦0</MenuItem>
                    <MenuItem value="low">₦1 - ₦1,000</MenuItem>
                    <MenuItem value="medium">₦1,001 - ₦10,000</MenuItem>
                    <MenuItem value="high">₦10,000+</MenuItem>
                  </Select>
                </Grid>

                <Grid
                  size={{ xs: 12, sm: 6, md: 4, lg: 3 }}
                  sx={{ display: "flex", alignItems: "flex-end" }}
                >
                  <Button
                    fullWidth
                    variant="outlined"
                    onClick={clearFilters}
                    size="medium"
                    startIcon={<ClearAll />}
                    disabled={
                      dateJoinedFilter === "all" &&
                      lastLoginFilter === "all" &&
                      balanceFilter === "all"
                    }
                  >
                    Clear Filters
                  </Button>
                </Grid>
              </Grid>
            </CardContent>
          </Card>
        )}

        <Box
          sx={{
            display: "flex",
            justifyContent: "space-between",
            alignItems: "center",
            mb: 2,
          }}
        >
          <Typography variant="body1" color="text.secondary">
            Showing <strong>{filteredUsers.length}</strong> of{" "}
            <strong>{users.length}</strong> users
          </Typography>
          {filteredUsers.length === 0 && (
            <Button
              variant="text"
              onClick={clearFilters}
              startIcon={<ClearAll />}
            >
              Clear filters
            </Button>
          )}
        </Box>
      </Box>

      {/* Users Grid */}
      {filteredUsers.length > 0 ? (
        <Grid container spacing={3}>
          {filteredUsers.map((user) => (
            <Grid size={{ xs: 12, sm: 6, md: 4, lg: 3 }} key={String(user._id)}>
              <UserCard
                user={user}
                onViewProfile={handleViewProfile}
                onDelete={handleDeleteUser}
              />
            </Grid>
          ))}
        </Grid>
      ) : (
        <Card sx={{ p: 4, textAlign: "center", borderRadius: 2 }}>
          <Box sx={{ maxWidth: 400, mx: "auto", py: 4 }}>
            <Person sx={{ fontSize: 60, color: "text.disabled", mb: 2 }} />
            <Typography variant="h6" gutterBottom>
              No users found
            </Typography>
            <Typography variant="body1" color="text.secondary" sx={{ mb: 3 }}>
              {searchQuery
                ? "No users match your search criteria"
                : "No users match your current filters"}
            </Typography>
            <Button
              variant="contained"
              onClick={clearFilters}
              startIcon={<ClearAll />}
            >
              Clear all filters
            </Button>
          </Box>
        </Card>
      )}

      {/* User Profile Dialog */}
      <Dialog
        open={!!selectedUser}
        onClose={() => setSelectedUser(null)}
        maxWidth="md"
        fullWidth
        PaperProps={{
          sx: {
            borderRadius: 3,
            backgroundImage: "none",
          },
        }}
      >
        {selectedUser && (
          <>
            <DialogTitle
              sx={{
                bgcolor: "background.paper",
                borderBottom: 1,
                borderColor: "divider",
                py: 2,
                px: 3,
                display: "flex",
                justifyContent: "space-between",
                alignItems: "center",
              }}
            >
              <Typography variant="h5" fontWeight={600}>
                User Profile
              </Typography>
              <IconButton onClick={() => setSelectedUser(null)}>
                <Close />
              </IconButton>
            </DialogTitle>
            <DialogContent dividers sx={{ p: 0 }}>
              <Grid container>
                <Grid
                  size={{ xs: 12, sm: 4 }}
                  sx={{
                    bgcolor: "background.default",
                    p: 3,
                    display: "flex",
                    flexDirection: "column",
                    alignItems: "center",
                    borderRight: { sm: 1 },
                    borderColor: { sm: "divider" },
                  }}
                >
                  <Avatar
                    src={selectedUser.image}
                    sx={{
                      width: 120,
                      height: 120,
                      fontSize: 48,
                      mb: 3,
                    }}
                  >
                    {selectedUser.name?.charAt(0) || "U"}
                  </Avatar>
                  <Typography variant="h6" fontWeight={600} gutterBottom>
                    {selectedUser.name}
                  </Typography>
                  <Chip
                    label={selectedUser.role || "user"}
                    color={
                      selectedUser.role === "admin" ? "primary" : "default"
                    }
                    size="small"
                    sx={{ mb: 3, textTransform: "capitalize" }}
                  />
                  <Box sx={{ width: "100%", textAlign: "center" }}>
                    <Button
                      variant="contained"
                      fullWidth
                      onClick={() => {
                        // Add action for message button
                      }}
                    >
                      Send Message
                    </Button>
                  </Box>
                </Grid>
                <Grid size={{ xs: 12, sm: 8 }} sx={{ p: 3 }}>
                  <Grid container spacing={2}>
                    <Grid size={{ xs: 12 }}>
                      <Typography
                        variant="subtitle1"
                        fontWeight={600}
                        gutterBottom
                      >
                        Basic Information
                      </Typography>
                      <Divider sx={{ mb: 2 }} />
                    </Grid>

                    <Grid size={{ xs: 12, sm: 6 }}>
                      <ProfileDetail
                        icon={<AccountCircle color="action" />}
                        label="Username"
                        value={selectedUser.username || "N/A"}
                      />
                    </Grid>
                    <Grid size={{ xs: 12, sm: 6 }}>
                      <ProfileDetail
                        icon={<Email color="action" />}
                        label="Email"
                        value={selectedUser.email}
                      />
                    </Grid>
                    <Grid size={{ xs: 12, sm: 6 }}>
                      <ProfileDetail
                        icon={<Phone color="action" />}
                        label="Phone Number"
                        value={selectedUser.mobileNumber || "N/A"}
                      />
                    </Grid>
                    <Grid size={{ xs: 12, sm: 6 }}>
                      <ProfileDetail
                        icon={<CalendarToday color="action" />}
                        label="Date Joined"
                        value={format(
                          new Date(selectedUser.dateJoined),
                          "MMM d, yyyy"
                        )}
                      />
                    </Grid>
                    <Grid size={{ xs: 12, sm: 6 }}>
                      <ProfileDetail
                        icon={<Schedule color="action" />}
                        label="Last Login"
                        value={
                          selectedUser.lastLogin
                            ? format(
                                new Date(selectedUser.lastLogin),
                                "MMM d, yyyy h:mm a"
                              )
                            : "Never logged in"
                        }
                      />
                    </Grid>
                    <Grid size={{ xs: 12, sm: 6 }}>
                      <ProfileDetail
                        icon={<AccountBalanceWallet color="action" />}
                        label="Wallet Balance"
                        value={`₦${
                          selectedUser.accountBalance?.toLocaleString() || "0"
                        }`}
                      />
                    </Grid>

                    <Grid size={{ xs: 12 }}>
                      <Typography
                        variant="subtitle1"
                        fontWeight={600}
                        gutterBottom
                        sx={{ mt: 2 }}
                      >
                        Account Details
                      </Typography>
                      <Divider sx={{ mb: 2 }} />
                    </Grid>

                    <Grid size={{ xs: 12, sm: 6 }}>
                      <ProfileDetail
                        icon={<VerifiedUser color="action" />}
                        label="User Type"
                        value={selectedUser.userType || "Regular"}
                      />
                    </Grid>
                    <Grid size={{ xs: 12, sm: 6 }}>
                      <ProfileDetail
                        icon={<Star color="action" />}
                        label="Referral Bonus"
                        value={`₦${
                          selectedUser.refererBonus?.toLocaleString() || "0"
                        }`}
                      />
                    </Grid>
                    <Grid size={{ xs: 12 }}>
                      <ProfileDetail
                        icon={null}
                        label="Status"
                        value={
                          <Chip
                            label={
                              selectedUser.transactionStatus
                                ? "Active"
                                : "Inactive"
                            }
                            color={
                              selectedUser.transactionStatus
                                ? "success"
                                : "error"
                            }
                            size="small"
                          />
                        }
                      />
                    </Grid>
                  </Grid>
                </Grid>
              </Grid>
            </DialogContent>
            <DialogActions sx={{ p: 2, borderTop: 1, borderColor: "divider" }}>
              <Button
                onClick={() => setSelectedUser(null)}
                variant="outlined"
                size="large"
              >
                Close
              </Button>
              <Button
                variant="contained"
                size="large"
                onClick={() => {
                  // Add action for edit button
                }}
              >
                Edit Profile
              </Button>
            </DialogActions>
          </>
        )}
      </Dialog>
    </Box>
  );
};

// Helper component for profile details
const ProfileDetail = ({
  icon,
  label,
  value,
}: {
  icon: React.ReactNode;
  label: string;
  value: React.ReactNode;
}) => (
  <Box sx={{ display: "flex", alignItems: "center", gap: 2, mb: 2 }}>
    {icon && (
      <Box
        sx={{
          width: 40,
          height: 40,
          display: "flex",
          alignItems: "center",
          justifyContent: "center",
          bgcolor: "action.hover",
          borderRadius: 1,
        }}
      >
        {icon}
      </Box>
    )}
    <Box>
      <Typography variant="caption" color="text.secondary">
        {label}
      </Typography>
      <Typography variant="body1">{value}</Typography>
    </Box>
  </Box>
);

export default UsersPage;
