'use client';

import React, { useCallback, useEffect, useMemo, useState } from 'react';
import dayjs, { Dayjs } from 'dayjs';
import timezone from 'dayjs/plugin/timezone';
import utc from 'dayjs/plugin/utc';
import { Calendar, CalendarProps, dayjsLocalizer, View, Views } from 'react-big-calendar';

import 'react-big-calendar/lib/css/react-big-calendar.css';

import { usePathname, useRouter, useSearchParams } from 'next/navigation';
import { fetchEvents } from '@/services/events.service';
import { getAllOrders, updateOrderStatus } from '@/services/order.service';
import CalendarMonthIcon from '@mui/icons-material/CalendarMonth';
import ReorderIcon from '@mui/icons-material/Reorder';
import SearchIcon from '@mui/icons-material/Search';
import TuneIcon from '@mui/icons-material/Tune';
import VisibilityIcon from '@mui/icons-material/Visibility';
import PersonIcon from '@mui/icons-material/Person';
import {
  Box,
  Button,
  ButtonGroup,
  Chip,
  Drawer,
  FormControl,
  IconButton,
  InputAdornment,
  InputLabel,
  OutlinedInput,
  Stack,
  Typography,
  useTheme,
  Paper,
  Table,
  TableBody,
  TableCell,
  TableContainer,
  TableHead,
  TableRow,
  TablePagination,
  Avatar,
} from '@mui/material';
import { DatePicker } from '@mui/x-date-pickers';
import { enqueueSnackbar } from 'notistack';

import { IOrder } from '@/types/order.type';
import CalendarComponent from '@/components/dashboard/events/calendar';
// import AddEventModal from './addEventModal';
import { CustomTable } from '@/components/dashboard/table';
import { getAllUsers, exportUsersToCSV } from '@/services/user.service';
import { UserProfile } from '@/types/user';
import { GetApp as ExportIcon } from '@mui/icons-material';
import { AppLoader } from '@/components/core/app-loader';

dayjs.extend(utc);
dayjs.extend(timezone);

// Day.js Localizer
const localizer = dayjsLocalizer(dayjs);

type Event = {
  id: number;
  title: string;
  start: Date;
  end: Date;
  eventUsersCount: number;
};

const tableColumns = [
  {
    title: 'Email',
    width: 180,
    isSort: true,
    key: 'emailAddress',
  },
  {
    title: 'Signup Date',
    width: 200,
    isSort: true,
    key: 'createdAt',
  },
  {
    title: 'Last Login',
    width: 200,
    isSort: true,
    key: 'lastLogin',
  },
  {
    title: 'Status',
    width: 200,
    isSort: true,
    key: 'isProfileCompleted',
  },
  {
    title: 'Actions',
    width: 50,
    isSort: false,
    key: 'actions',
  },
];

const Users: React.FC = () => {
  const [myEvents, setEvents] = useState<Event[]>([]);
  const [currentDate, setCurrentDate] = useState<Date>(new Date());
  const [currentView, setCurrentView] = useState<View>('month');
  const [isModalOpen, setIsModalOpen] = useState(false);
  const [isLoading, setIsLoading] = useState(false);
  const [data, setData] = React.useState<UserProfile[]>([]);
  const [users, setUsers] = React.useState<UserProfile[]>([]);
  const [total, setTotal] = useState(0);
  const [search, setSearch] = useState<string>('');
  const [rowsPerPage, setRowsPerPage] = useState<number>(50);
  const [page, setPage] = useState<number>(0);
  const [order, setOrder] = useState<'asc' | 'desc'>('desc');
  const [orderBy, setOrderBy] = useState<string>('createdAt');
  const [refreshSelectedOrganizations, setRefreshSelectedOrganizations] = useState<boolean>(false);
  const [open, setOpen] = React.useState(false);
  const [view, setView] = React.useState<'list' | 'calendar'>('calendar');
  const [eventType, setEventType] = React.useState<'upcoming' | 'completed'>('upcoming');

  const [selectedDate, setSelectedDate] = useState<Dayjs | null | undefined>(dayjs(new Date()));
  const router = useRouter();
  const searchParams = useSearchParams();
  const pathname = usePathname();

  useEffect(() => {
    const param = searchParams.get('event_modal');

    // Open the modal if the "modal" parameter is present
    if (param) {
      setIsModalOpen(true);
    } else {
      setIsModalOpen(false);
    }
  }, [searchParams]);
  const openModal = () => {
    router.replace(`?event_modal=1`); // Add a `modal` query param to the route
  };
  const closeSlotModal = () => {
    setIsModalOpen(false);
    // Remove the `modal` query param while preserving dynamic path
    const currentParams = new URLSearchParams(searchParams);
    currentParams.delete('event_modal');

    const newUrl = `${pathname}${currentParams.toString() ? `?${currentParams}` : ''}`;
    router.replace(newUrl); // Remove the `modal` query param from the route
  };

  const theme = useTheme(); // Get the MUI theme
  const primaryColor = theme.palette.primary.main; // Access the primary color
  // Handle change of the selected date
  const handleDateChange = (date: Dayjs | null) => {
    setSelectedDate(date);
    if (date) {
      setCurrentDate(date.toDate());
    }
  };

  const handleSelectEvent = useCallback((event: Event) => {
    window.alert(`Event: ${event.title}`);
  }, []);

  const handleNavigate = useCallback((date: Date) => {
    setCurrentDate(date);
  }, []);

  const handleViewChange = useCallback((view: View) => {
    setCurrentView(view);
    if (view === 'month') {
      setCurrentDate(new Date()); // Reset to current month if month view is selected
    }
  }, []);

  const handleYearChange = useCallback((yearChange: number) => {
    setCurrentDate((prev) => {
      const newDate = dayjs(prev).add(yearChange, 'year');
      return newDate.toDate();
    });
  }, []);

  const { defaultDate, scrollToTime } = useMemo(
    () => ({
      defaultDate: new Date(),
      scrollToTime: new Date(1970, 1, 1, 6),
    }),
    []
  );

  const eventStyleGetter = useCallback(
    (event: Event) => {
      // Apply the primary color to the event background
      let backgroundColor = primaryColor; // Default to primary color

      if (event.title.toLowerCase().includes('project')) {
        backgroundColor = '#e91e63'; // Override background color for Project events
      } else if (event.title.toLowerCase().includes('meeting')) {
        backgroundColor = '#4caf50'; // Override background color for Meeting events
      }

      return {
        style: {
          backgroundColor, // Use primaryColor from MUI theme
          color: '#fff', // White text for better contrast on colored backgrounds
        },
      };
    },
    [primaryColor] // Make sure to memoize with primaryColor
  );


  const fetchUsers = async () => {
    try {
      setIsLoading(true);
      const response = await getAllUsers({
        limit: rowsPerPage,
        offset: page * rowsPerPage,
        search: search,
        sort: order,
        sortField: orderBy,
      });
      console.log(response, 'Users Response');
      const usersData = response?.data?.data?.users || [];
      setUsers(usersData);
      setTotal(response?.data?.data?.count || 0);
      setIsLoading(false);
    } catch (error) {
      console.error('Error fetching organizations:', error);
      setIsLoading(false);
    }
  };

  React.useEffect(() => {
    fetchUsers().then(() => {
      //   setRefreshSelectedOrganizations(true);
    });
  }, [rowsPerPage, page, order, orderBy, search]);

  const handlePageChange = (event: unknown, newPage: number) => {
    setPage(newPage);
  };
  const handleRowsPerPageChange = (event: React.ChangeEvent<HTMLInputElement>) => {
    setRowsPerPage(parseInt(event.target.value, 10));
    setPage(0);
  };

  const handleSort = (sortField: any, sort: string) => {
    console.log(sortField, sort, 'Sorting');
    const isAsc = orderBy === sort && order === 'asc';
    console.log(isAsc, 'IS ASC');
    setOrder(isAsc ? 'desc' : 'asc');
    setOrderBy(sort);
    setPage(0);
  };

  const handleSelected = (selected: string[]) => {
    // setSelectedOrganizations(selected);

    setRefreshSelectedOrganizations(false);
  };

  const handleExport = () => {
    if (users.length > 0) {
      exportUsersToCSV(users);
      enqueueSnackbar('Users exported successfully', { variant: 'success' });
    } else {
      enqueueSnackbar('No users to export', { variant: 'warning' });
    }
  };

  return (
    <Box sx={{ minHeight: '100vh', p: 3 }}>
      {/* Modern Header Section */}
      <Stack
        direction="row"
        justifyContent="space-between"
        alignItems="center"
        sx={{
          mb: 4,
          p: 3,
          borderRadius: 4,
          background: '#FFDD31',
          color: '#0B0504',
        }}
      >
        <Box>
          <Typography variant="h4" fontWeight={700} gutterBottom>
            User Management
          </Typography>
          <Typography variant="body1" sx={{ opacity: 0.9 }}>
            Manage and monitor registered users and their profiles
          </Typography>
        </Box>
        <Stack direction="row" spacing={2} alignItems="center">
          <Button
            variant="contained"
            startIcon={<ExportIcon />}
            onClick={handleExport}
            disabled={users.length === 0}
            sx={{
              bgcolor: 'rgba(11, 5, 4, 0.8)',
              color: '#FFDD31',
              borderRadius: 3,
              px: 3,
              py: 1.5,
              fontWeight: 600,
              border: '1px solid rgba(11, 5, 4, 0.9)',
              '&:hover': {
                bgcolor: 'rgba(11, 5, 4, 0.9)',
                transform: 'translateY(-2px)',
              },
              transition: 'all 0.3s ease',
              '&:disabled': {
                bgcolor: 'rgba(11, 5, 4, 0.3)',
                color: 'rgba(255, 221, 49, 0.5)',
                border: '1px solid rgba(11, 5, 4, 0.2)',
              },
            }}
          >
            Export CSV
          </Button>
          <FormControl sx={{ minWidth: 300 }}>
            <OutlinedInput
              placeholder="Search users by name, email..."
              value={search}
              onChange={(e) => setSearch(e.target.value)}
              sx={{
                bgcolor: 'background.paper',
                borderRadius: 3,
                '& .MuiOutlinedInput-notchedOutline': {
                  borderColor: theme.palette.mode === 'dark' ? '#4a5568' : '#e2e8f0',
                },
                '&:hover .MuiOutlinedInput-notchedOutline': {
                  borderColor: theme.palette.mode === 'dark' ? '#718096' : '#cbd5e0',
                },
                '&.Mui-focused .MuiOutlinedInput-notchedOutline': {
                  borderColor: '#667eea',
                  borderWidth: 2,
                },
              }}
              endAdornment={
                <InputAdornment position="end">
                  <IconButton edge="end" sx={{ color: 'primary.main' }}>
                    <SearchIcon />
                  </IconButton>
                </InputAdornment>
              }
            />
          </FormControl>
        </Stack>
      </Stack>
      {/* Modern Users Table */}
      <Paper
        elevation={0}
        sx={{
          borderRadius: 4,
          background: theme.palette.mode === 'dark' 
            ? 'linear-gradient(145deg, #1a202c 0%, #2d3748 100%)' 
            : 'linear-gradient(145deg, #ffffff 0%, #f8fafc 100%)',
          border: theme.palette.mode === 'dark'
            ? '1px solid #4a5568'
            : '1px solid rgba(255, 255, 255, 0.2)',
          boxShadow: '0 8px 32px rgba(0, 0, 0, 0.08)',
          overflow: 'hidden',
          position: 'relative',
          minHeight: 400,
        }}
      >
        {isLoading && (
          <AppLoader fill size="lg" label="Loading users..." />
        )}
        
        <TableContainer>
          <Table>
            <TableHead>
              <TableRow
                sx={{
                  '& .MuiTableCell-head': {
                    backgroundColor: theme.palette.mode === 'dark' ? '#2d3748' : '#f8fafc',
                    fontWeight: 600,
                    color: 'text.primary',
                    borderBottom: theme.palette.mode === 'dark' 
                      ? '2px solid #4a5568' 
                      : '2px solid #e5e7eb',
                    py: 2,
                  }
                }}
              >
                <TableCell>Email</TableCell>
                <TableCell>Signup Date</TableCell>
                <TableCell>Last Login</TableCell>
                <TableCell>Status</TableCell>
                <TableCell align="center">Actions</TableCell>
              </TableRow>
            </TableHead>
            <TableBody>
              {Array.isArray(users) && users.length > 0 ? (
                users.map((user) => (
                  <TableRow 
                    key={user._id}
                    sx={{
                      '&:hover': {
                        backgroundColor: theme.palette.mode === 'dark' ? '#2d3748' : '#f8fafc',
                        transform: 'scale(1.001)',
                        transition: 'all 0.2s ease-in-out',
                      },
                      '& .MuiTableCell-root': {
                        borderBottom: theme.palette.mode === 'dark' 
                          ? '1px solid #4a5568' 
                          : '1px solid #f1f5f9',
                        py: 2,
                      }
                    }}
                  >
                    <TableCell>
                      <Typography variant="body2" fontWeight={500}>
                        {user.emailAddress || 'No email'}
                      </Typography>
                    </TableCell>
                    <TableCell>
                      <Typography variant="body2">
                        {user.createdAt 
                          ? new Date(user.createdAt).toLocaleDateString('en-US', {
                              month: 'short',
                              day: 'numeric',
                              year: 'numeric'
                            })
                          : 'Unknown'
                        }
                      </Typography>
                    </TableCell>
                    <TableCell>
                      <Typography variant="body2">
                        {user.lastLogin 
                          ? new Date(user.lastLogin).toLocaleDateString('en-US', {
                              month: 'short',
                              day: 'numeric',
                              year: 'numeric'
                            })
                          : 'Never'
                        }
                      </Typography>
                    </TableCell>
                    <TableCell>
                      <Chip
                        label={user.isProfileCompleted ? 'Active' : 'Inactive'}
                        color={user.isProfileCompleted ? 'success' : 'warning'}
                        size="small"
                        variant="filled"
                        sx={{
                          fontWeight: 600,
                          minWidth: 90,
                          '&.MuiChip-colorSuccess': {
                            backgroundColor: '#dcfce7',
                            color: '#166534',
                          },
                          '&.MuiChip-colorWarning': {
                            backgroundColor: '#fef3c7',
                            color: '#d97706',
                          },
                        }}
                      />
                    </TableCell>
                    <TableCell align="center">
                      <IconButton
                        size="small"
                        onClick={() => router.push(`users/${user._id}`)}
                        sx={{
                          color: 'primary.main',
                          '&:hover': {
                            backgroundColor: 'primary.50',
                            transform: 'scale(1.1)',
                          },
                          transition: 'all 0.2s ease-in-out',
                        }}
                        title="View Details"
                      >
                        <VisibilityIcon />
                      </IconButton>
                    </TableCell>
                  </TableRow>
                ))
              ) : (
                <TableRow>
                  <TableCell colSpan={5} align="center" sx={{ py: 8 }}>
                    <Stack alignItems="center" spacing={2}>
                      <Box
                        sx={{
                          width: 64,
                          height: 64,
                          borderRadius: '50%',
                          backgroundColor: theme.palette.mode === 'dark' ? '#4a5568' : '#f3f4f6',
                          display: 'flex',
                          alignItems: 'center',
                          justifyContent: 'center',
                        }}
                      >
                        <PersonIcon sx={{ fontSize: 32, color: 'text.secondary' }} />
                      </Box>
                      <Typography variant="h6" color="text.secondary">
                        No users found
                      </Typography>
                      <Typography variant="body2" color="text.secondary">
                        Users will appear here when they register
                      </Typography>
                    </Stack>
                  </TableCell>
                </TableRow>
              )}
            </TableBody>
          </Table>
        </TableContainer>
        
        {/* Modern Pagination */}
        <Box sx={{ p: 2, borderTop: theme.palette.mode === 'dark' ? '1px solid #4a5568' : '1px solid #f1f5f9' }}>
          <TablePagination
            component="div"
            count={total}
            page={page}
            onPageChange={handlePageChange}
            rowsPerPage={rowsPerPage}
            onRowsPerPageChange={handleRowsPerPageChange}
            sx={{
              '& .MuiTablePagination-toolbar': {
                px: 0,
              },
              '& .MuiTablePagination-selectLabel, & .MuiTablePagination-displayedRows': {
                fontWeight: 500,
                color: 'text.secondary',
              },
              '& .MuiIconButton-root': {
                color: 'text.secondary',
                '&:hover': {
                  backgroundColor: theme.palette.mode === 'dark' ? '#4a5568' : '#f3f4f6',
                },
                '&.Mui-disabled': {
                  color: theme.palette.mode === 'dark' ? '#718096' : '#d1d5db',
                },
              },
            }}
          />
        </Box>
      </Paper>
    </Box>
  );
};

export default Users;
