"use client";

import { useState, useEffect } from 'react';
import { 
  Container, Typography, Card, CardHeader, Box, 
  TextField, MenuItem, Table, TableBody, TableCell, 
  TableContainer, TableHead, TableRow, Avatar, Chip, 
  Button, IconButton, Tooltip, Paper, Pagination
} from '@mui/material';
import { useRouter } from 'next/navigation';
import { paths } from '@/routes/paths';
import axiosInstancee from '@/utils/axios';
import { useSnackbar } from '@/components/snackbar';
import SearchIcon from '@mui/icons-material/Search';
import RefreshIcon from '@mui/icons-material/Refresh';
import AssignmentIndIcon from '@mui/icons-material/AssignmentInd';
import CustomBreadcrumbs from '@/components/custom-breadcrumbs';
import axios from 'axios';
import ConditionalComponent from "@/shared/components/ConditionalComponent";

type User = {
  id: number;
  firstName: string;
  lastName: string;
  email: string;
  phoneNumber: string | null;
  state: string;
  picture: string | null;
  createDate: any;
  role: string | null;
  agency: any;
};

export default function UnassignedUsersPage() {
  const router = useRouter();
  const { enqueueSnackbar } = useSnackbar();
  
  const [users, setUsers] = useState<User[]>([]);
  const [filteredUsers, setFilteredUsers] = useState<User[]>([]);
  const [isLoading, setIsLoading] = useState(true);
  const [searchQuery, setSearchQuery] = useState('');
  const [statusFilter, setStatusFilter] = useState('all');
  const [page, setPage] = useState(1);
  const [rowsPerPage] = useState(10);

  const fetchUsers = async () => {
    setIsLoading(true);
    try {
      const response = await axiosInstancee.get('/api/user/unassigned');
      const unassignedUsers = response.data;
    
      
      unassignedUsers.sort((a: User, b: User) => {
        const dateA = Array.isArray(a.createDate) ? 
          new Date(a.createDate[0], a.createDate[1]-1, a.createDate[2]) : 
          new Date(a.createDate);
        
        const dateB = Array.isArray(b.createDate) ? 
          new Date(b.createDate[0], b.createDate[1]-1, b.createDate[2]) : 
          new Date(b.createDate);
        
        return dateB.getTime() - dateA.getTime();
      });
      
      setUsers(unassignedUsers);
    } catch (error) {
      console.error('Error fetching unassigned users:', error);
      enqueueSnackbar('Failed to load unassigned users', { variant: 'error' });
    } finally {
      setIsLoading(false);
    }
  };

  useEffect(() => {
    fetchUsers();
  }, []);

  useEffect(() => {
    const filtered = users.filter(user => {
      // Search filter
      const matchesSearch = 
        searchQuery === '' || 
        user.firstName?.toLowerCase().includes(searchQuery.toLowerCase()) ||
        user.lastName?.toLowerCase().includes(searchQuery.toLowerCase()) ||
        user.email?.toLowerCase().includes(searchQuery.toLowerCase());
      
      // Status filter
      const matchesStatus = 
        statusFilter === 'all' || 
        user.state === statusFilter;
      
      return matchesSearch && matchesStatus;
    });
    
    setFilteredUsers(filtered);
  }, [users, searchQuery, statusFilter]);

  const formatDate = (dateArray: any) => {
    if (!dateArray) return 'N/A';
    try {
      if (Array.isArray(dateArray) && dateArray.length >= 3) {
        const [year, month, day] = dateArray;
        return new Date(year, month - 1, day).toLocaleDateString();
      }
      return new Date(dateArray).toLocaleDateString();
    } catch (error) {
      return 'Invalid Date';
    }
  };

  const handleAssignUser = (userId: number) => {
 
    const selectedAgency = localStorage.getItem("selectedAgency");
    
    // If there's a selected agency, include it in the URL parameters
    if (selectedAgency) {
      router.push(`${paths.dashboard.agency.createUserAgency}?userId=${userId}&agencyId=${selectedAgency}`);
    } else {
      router.push(`${paths.dashboard.agency.createUserAgency}?userId=${userId}`);
    }
  };

  const handleChangePage = (event: React.ChangeEvent<unknown>, newPage: number) => {
    setPage(newPage);
  };

  // Calculate pagination
  const totalPages = Math.ceil(filteredUsers.length / rowsPerPage);
  const paginatedUsers = filteredUsers.slice(
    (page - 1) * rowsPerPage,
    page * rowsPerPage
  );

  if (users.length === 0 && !isLoading) {
    return (
      <Container maxWidth={false}>
        <CustomBreadcrumbs
          heading="Unassigned Users"
          links={[
            { name: 'Dashboard', href: paths.dashboard.root },
            { name: 'Users', href: paths.dashboard.user.root },
            { name: 'Unassigned Users' },
          ]}
          action={
            <Tooltip title="Refresh">
              <IconButton onClick={fetchUsers}>
                <RefreshIcon />
              </IconButton>
            </Tooltip>
          }
          sx={{ mb: 3 }}
        />
        <Card>
          <CardHeader 
            title="No Unassigned Users" 
            subheader="All users have been assigned to agencies"
          />
          <Box sx={{ p: 3, textAlign: 'center' }}>
            <Typography variant="body1">
              There are currently no unassigned users in the system.
            </Typography>
            <Button 
              variant="contained" 
              sx={{ mt: 2 }}
              onClick={() => router.push(paths.dashboard.user.root)}
            >
              View All Users
            </Button>
          </Box>
        </Card>
      </Container>
    );
  }

  return (
    <Container maxWidth={false}>
      <CustomBreadcrumbs
        heading="Unassigned Users"
        links={[
          { name: 'Dashboard', href: paths.dashboard.root },
          { name: 'Users', href: paths.dashboard.user.root },
          { name: 'Unassigned Users' },
        ]}
        action={
          <Tooltip title="Refresh">
            <IconButton onClick={fetchUsers}>
              <RefreshIcon />
            </IconButton>
          </Tooltip>
        }
        sx={{ mb: 3 }}
      />

      <Card>
        <CardHeader 
          title="Newly Registered Users" 
          subheader="Users who haven't been assigned to any agency or role"
        />
        
        <Box sx={{ px: 3, py: 2, display: 'flex', gap: 2, flexWrap: 'wrap' }}>
          <TextField
            size="small"
            label="Search"
            value={searchQuery}
            onChange={(e) => setSearchQuery(e.target.value)}
            InputProps={{
              startAdornment: <SearchIcon fontSize="small" sx={{ mr: 1, color: 'text.disabled' }} />,
            }}
            sx={{ minWidth: 240 }}
          />
          <TextField
            select
            size="small"
            label="Status"
            value={statusFilter}
            onChange={(e) => setStatusFilter(e.target.value)}
            sx={{ minWidth: 150 }}
          >
            <MenuItem value="all">All</MenuItem>
            <MenuItem value="ACTIVE">Active</MenuItem>
            <MenuItem value="INACTIVE">Inactive</MenuItem>
          </TextField>
        </Box>
        
        <TableContainer>
          <Table>
            <TableHead>
              <TableRow>
                <TableCell>Name</TableCell>
                <TableCell>Email</TableCell>
                <TableCell>Status</TableCell>
                <TableCell>Created</TableCell>
                <TableCell align="right">Actions</TableCell>
              </TableRow>
            </TableHead>
            <TableBody>
              <ConditionalComponent 
                isValid={isLoading}
                defaultComponent={
                  <ConditionalComponent 
                    isValid={paginatedUsers.length === 0}
                    defaultComponent={
                      <>
                        {paginatedUsers.map((user) => (
                          <TableRow key={user.id}>
                            <TableCell>
                              <Box sx={{ display: 'flex', alignItems: 'center' }}>
                                <Avatar 
                                  src={user.picture && !user.picture.includes('null') && !user.picture.includes('default.jpg') ? user.picture : ''}
                                  alt={`${user.firstName} ${user.lastName}`}
                                  sx={{ 
                                    width: 36, 
                                    height: 36, 
                                    mr: 1.5,
                                    bgcolor: (theme) => {
                                      const colors = [
                                        theme.palette.primary.main,
                                        theme.palette.info.main,
                                        theme.palette.success.main,
                                        theme.palette.warning.main,
                                        theme.palette.error.main,
                                      ];
                                      return colors[user.id % colors.length];
                                    }
                                  }}
                                >
                                  {user.firstName && user.lastName ? `${user.firstName[0]}${user.lastName[0]}` : '?'}
                                </Avatar>
                                <Typography variant="body2" sx={{ fontWeight: 'medium' }}>
                                  {user.firstName} {user.lastName}
                                </Typography>
                              </Box>
                            </TableCell>
                            <TableCell>{user.email}</TableCell>
                            <TableCell>
                              <Chip 
                                label={user.state} 
                                size="small"
                                color={user.state === 'ACTIVE' ? 'success' : 'default'}
                              />
                            </TableCell>
                            <TableCell>{formatDate(user.createDate)}</TableCell>
                            <TableCell align="right">
                              <Button
                                variant="outlined"
                                size="small"
                                startIcon={<AssignmentIndIcon />}
                                onClick={() => handleAssignUser(user.id)}
                              >
                                Assign to Agency
                              </Button>
                            </TableCell>
                          </TableRow>
                        ))}
                      </>
                    }
                  >
                    <TableRow>
                      <TableCell colSpan={5} align="center">No unassigned users found</TableCell>
                    </TableRow>
                  </ConditionalComponent>
                }
              >
                <TableRow>
                  <TableCell colSpan={5} align="center">Loading...</TableCell>
                </TableRow>
              </ConditionalComponent>
            </TableBody>
          </Table>
        </TableContainer>
        
        <ConditionalComponent isValid={totalPages > 1}>
          <Box sx={{ display: 'flex', justifyContent: 'center', py: 3 }}>
            <Pagination 
              count={totalPages} 
              page={page} 
              onChange={handleChangePage} 
              color="primary" 
            />
          </Box>
        </ConditionalComponent>
      </Card>
    </Container>
  );
} 