import { useForm } from 'react-hook-form';
import { useState, useEffect } from 'react';
import { Box, Card, Grid, MenuItem, TextField, Typography, Avatar } from '@mui/material';
import LoadingButton from '@mui/lab/LoadingButton';
import axiosInstance, { axiosInstancee } from '@/utils/axios';
import { useSnackbar } from '@/components/snackbar';
import { useRouter, useSearchParams } from 'next/navigation';
import { paths } from '@/routes/paths';
import { generateToken } from '@/utils/firebase';
import { alpha } from '@mui/material/styles';
import SearchIcon from '@mui/icons-material/Search';
import PersonAddIcon from '@mui/icons-material/PersonAdd';
import BusinessIcon from '@mui/icons-material/Business';
import AdminPanelSettingsIcon from '@mui/icons-material/AdminPanelSettings';

type Agency = {
  id: number;
  name: string;
};

type User = {
  id: number;
  firstName: string;
  lastName: string;
  email: string;
  phoneNumber: string | null;
  state: string;
  picture?: string;
};

type FormData = {
  agencyId: number;
  role: string;
  userId: number;
};

const roleOptions = [
  { value: 'ADMIN', label: 'Admin' },
  { value: 'MANAGER', label: 'Agency Manager' },
  { value: 'COLLABORATOR', label: 'Collaborator' },
  { value: 'CLIENT', label: 'Client' },
];

export default function AddUserToAgencyForm() {
  const router = useRouter();
  const searchParams = useSearchParams();
  const preselectedUserId = searchParams.get('userId');
  const preselectedAgencyId = searchParams.get('agencyId');

  const { register, handleSubmit, setValue, watch, formState: { isSubmitting } } = useForm<FormData>();
  const { enqueueSnackbar } = useSnackbar();
  const [loading, setLoading] = useState(false);
  const [users, setUsers] = useState<User[]>([]);
  const [agencies, setAgencies] = useState<Agency[]>([]);
  const [searchQuery, setSearchQuery] = useState('');
  const [agencySearchQuery, setAgencySearchQuery] = useState('');
  const [isSearching, setIsSearching] = useState(false);
  const [selectedUser, setSelectedUser] = useState<User | null>(null);

  // Check if user is a manager
  const roles = JSON.parse(localStorage.getItem("role") || "[]");
  const isManager = roles.includes("MANAGER");
  const isAdmin = roles.includes("ADMIN");

  useEffect(() => {
    const fetchAgencies = async () => {
      try {
        const response = await axiosInstancee.get('/api/user/api/v1/agency/approved');
        setAgencies(response.data);

        // If user is a manager and has a selected agency, auto-select it and disable the field
        if (isManager && !isAdmin) {
          const selectedAgency = localStorage.getItem("selectedAgency");
          if (selectedAgency) {
            setValue('agencyId', parseInt(selectedAgency, 10));
          }
        } else if (preselectedAgencyId) {
          // For admins, still respect the preselected agency if provided
          setValue('agencyId', parseInt(preselectedAgencyId, 10));
        }
      } catch (error) {
        console.error('Error fetching agencies:', error);
        enqueueSnackbar('Failed to load agencies', { variant: 'error' });
      }
    };
    fetchAgencies();
  }, [enqueueSnackbar, setValue, isManager, isAdmin, preselectedAgencyId]);

  useEffect(() => {
    const debounceTimeout = setTimeout(async () => {
      setIsSearching(true);
      try {
        if (searchQuery.trim().length >= 2) {
          const response = await axiosInstancee.get('/api/user/search', {
            params: { query: searchQuery }
          });
          setUsers(response.data);
        } else {
          const response = await axiosInstancee.get('/api/user/users');
          setUsers(response.data);

          if (preselectedUserId && !selectedUser) {
            const userId = parseInt(preselectedUserId, 10);
            const user = response.data.find((u: User) => u.id === userId);
            if (user) {
              handleUserSelect(user);
            }
          }
        }
      } catch (error) {
        console.error('Error fetching users:', error);
        enqueueSnackbar('Failed to load users', { variant: 'error' });
      } finally {
        setIsSearching(false);
      }
    }, 500);

    return () => clearTimeout(debounceTimeout);
  }, [searchQuery, enqueueSnackbar, preselectedUserId, selectedUser]);

  useEffect(() => {
    const fetchPreselectedUser = async () => {
      if (preselectedUserId) {
        setIsSearching(true);
        try {
          const response = await axiosInstancee.get(`/api/user/${preselectedUserId}`);


          if (response.data) {
            setSelectedUser(response.data);
            setValue('userId', parseInt(preselectedUserId, 10));
          }
        } catch (error) {

          enqueueSnackbar('Failed to load preselected user', { variant: 'error' });
        } finally {
          setIsSearching(false);
        }
      }
    };

    fetchPreselectedUser();
  }, [preselectedUserId, setValue, enqueueSnackbar]);

  useEffect(() => {
    if (isManager && !isAdmin) {
      const selectedAgencyId = localStorage.getItem("selectedAgency");


      if (selectedAgencyId) {
        setValue('agencyId', parseInt(selectedAgencyId, 10));


        const fetchSelectedAgencyName = async () => {
          try {

            const response = await axiosInstancee.get(`/api/user/agency/${selectedAgencyId}`);

            if (response.data) {
              setAgencies(prevAgencies => {
                const exists = prevAgencies.some(a => a.id.toString() === selectedAgencyId);

                if (!exists) {
                  return [...prevAgencies, response.data];
                }
                return prevAgencies;
              });
            }
          } catch (error) {
            console.error('Error fetching selected agency:', error);
          }
        };

        fetchSelectedAgencyName();
      }
    } else if (preselectedAgencyId) {

      setValue('agencyId', parseInt(preselectedAgencyId, 10));
    }
  }, [isManager, isAdmin, setValue, preselectedAgencyId]);

  const handleUserSelect = (user: User) => {
    setSelectedUser(user);
    setValue('userId', user.id);
    setSearchQuery('');

  };

  const onSubmit = async (data: FormData) => {
    setLoading(true);

    try {


      const addMemberResponse = await axiosInstancee.post('/api/user/add/member/agency', null, {
        params: {
          agencyId: data.agencyId,
          userId: data.userId,
          role: data.role,
        },
      });



      enqueueSnackbar('User added to agency successfully', { variant: 'success' });
      router.push(paths.dashboard.agency.list);
    } catch (error) {
      console.error("Error adding user to agency:", error); // Debug log
      enqueueSnackbar('Failed to add user to agency. Please try again.', { variant: 'error' });
    } finally {
      setLoading(false);
    }
  };



  return (
    <Box
      component="form"
      onSubmit={handleSubmit(onSubmit)}
      sx={{
        maxWidth: 800,
        margin: 'auto',
        mt: 5,
        px: 2
      }}
    >
      <Card
        sx={{
          p: 4,
          background: (theme) => alpha(theme.palette.background.default, 0.9),
          backdropFilter: 'blur(6px)',
          boxShadow: (theme) => theme.shadows[15],
          borderRadius: 2,
          transition: 'transform 0.3s ease-in-out',
          '&:hover': {
            transform: 'translateY(-4px)'
          }
        }}
      >
        <Box sx={{ mb: 4, textAlign: 'center' }}>
          <PersonAddIcon
            sx={{
              fontSize: 40,
              color: 'primary.main',
              mb: 2
            }}
          />
          <Typography variant="h4" gutterBottom>
            {selectedUser ? `Assign ${selectedUser.firstName} ${selectedUser.lastName} to Agency` : 'Add User to Agency'}
          </Typography>
          <Typography variant="body2" color="text.secondary">
            {selectedUser
              ? 'Select an agency and role for this user'
              : 'Search and assign users to your agency with specific roles'}
          </Typography>
        </Box>

        {selectedUser && (
          <Box sx={{ mb: 4, p: 2, bgcolor: 'action.hover', borderRadius: 1 }}>
            <Typography variant="subtitle2" gutterBottom>Selected User:</Typography>
            <Box sx={{ display: 'flex', alignItems: 'center', mt: 1 }}>
              <Avatar
                src={selectedUser.picture || ''}
                alt={`${selectedUser.firstName} ${selectedUser.lastName}`}
                sx={{ mr: 2, width: 48, height: 48 }}
              >
                {selectedUser.firstName && selectedUser.lastName ?
                  `${selectedUser.firstName[0]}${selectedUser.lastName[0]}` : '?'}
              </Avatar>
              <Box>
                <Typography variant="body1" fontWeight="medium">{`${selectedUser.firstName} ${selectedUser.lastName}`}</Typography>
                <Typography variant="body2" color="text.secondary">{selectedUser.email}</Typography>
                {selectedUser.phoneNumber && (
                  <Typography variant="body2" color="text.secondary">{selectedUser.phoneNumber}</Typography>
                )}
              </Box>
            </Box>
            <input type="hidden" {...register('userId')} value={selectedUser.id} />
          </Box>
        )}

        <Grid container spacing={3}>
          <Grid item xs={12}>
            <TextField
              select
              label="Select Agency"
              fullWidth
              value={watch('agencyId') || ''}
              onChange={(e) => {

                setValue('agencyId', parseInt(e.target.value, 10));
              }}
              InputProps={{
                startAdornment: (
                  <BusinessIcon sx={{ color: 'text.secondary', mr: 1 }} />
                ),
                readOnly: isManager && !isAdmin,
              }}
              disabled={isManager && !isAdmin}
              sx={{
                '& .MuiOutlinedInput-root': {
                  '&.Mui-focused fieldset': {
                    borderWidth: 2,
                  },
                  '&.Mui-disabled': {
                    backgroundColor: 'action.selected',
                    '& fieldset': {
                      borderColor: 'divider',
                    },
                  },
                },
              }}
              SelectProps={{
                MenuProps: {
                  PaperProps: {
                    sx: {
                      maxHeight: 450,
                    },
                  },
                },
                renderValue: (selected) => {
                  const agency = agencies.find(a => a.id === parseInt(selected as string, 10));
                  return agency ? agency.name : 'Select Agency';
                },
              }}
            >
              {agencies.map((agency) => (
                <MenuItem
                  key={agency.id}
                  value={agency.id}
                >
                  {agency.name}
                </MenuItem>
              ))}
            </TextField>
          </Grid>

          {!selectedUser && (
            <Grid item xs={12}>
              <TextField
                select
                label="Select User"
                fullWidth
                {...register('userId', { required: true })}
                InputProps={{
                  startAdornment: (
                    <PersonAddIcon sx={{ color: 'text.secondary', mr: 1 }} />
                  ),
                }}
                SelectProps={{
                  MenuProps: {
                    PaperProps: {
                      sx: {
                        maxHeight: 450,
                        '& .MuiMenuItem-root': {
                          px: 2,
                          py: 1,
                          borderRadius: 1,
                          mx: 1,
                          my: 0.5,
                        },
                      },
                    },
                  },
                }}
              >
                <MenuItem>
                  <TextField
                    size="small"
                    autoFocus
                    placeholder="Search users..."
                    fullWidth
                    value={searchQuery}
                    onChange={(e) => {
                      e.stopPropagation();
                      setSearchQuery(e.target.value);
                    }}
                    InputProps={{
                      startAdornment: (
                        <SearchIcon sx={{ color: 'text.secondary', mr: 1 }} />
                      ),
                    }}
                    onClick={(e) => e.stopPropagation()}
                    onKeyDown={(e) => e.stopPropagation()}
                  />
                </MenuItem>
                {isSearching ? (
                  <MenuItem disabled>
                    <Box sx={{ display: 'flex', alignItems: 'center', py: 1 }}>
                      <Typography>Loading users...</Typography>
                    </Box>
                  </MenuItem>
                ) : users.length === 0 ? (
                  <MenuItem disabled>
                    <Box sx={{ display: 'flex', alignItems: 'center', py: 1 }}>
                      <Typography>No users found</Typography>
                    </Box>
                  </MenuItem>
                ) : (
                  users.map((user) => (
                    <MenuItem
                      key={user.id}
                      value={user.id}
                      sx={{
                        transition: 'all 0.2s',
                        '&:hover': {
                          backgroundColor: 'action.hover',
                        },
                      }}
                    >
                      <Box sx={{ display: 'flex', flexDirection: 'column' }}>
                        <Typography>{`${user.firstName} ${user.lastName}`}</Typography>
                        <Typography variant="caption" color="text.secondary">
                          {user.email}
                        </Typography>
                      </Box>
                    </MenuItem>
                  ))
                )}
              </TextField>
            </Grid>
          )}

          <Grid item xs={12}>
            <TextField
              select
              label="Role"
              fullWidth
              defaultValue=""
              {...register('role', { required: true })}
              InputProps={{
                startAdornment: (
                  <AdminPanelSettingsIcon sx={{ color: 'text.secondary', mr: 1 }} />
                ),
              }}
              SelectProps={{
                displayEmpty: true,
                renderValue: (selected) => {
                  if (!selected) {
                    return <Typography color="text.secondary">Select a role</Typography>;
                  }
                  const role = roleOptions.find(option => option.value === selected);
                  return role ? role.label : String(selected);
                },
                MenuProps: {
                  PaperProps: {
                    sx: {
                      maxHeight: 450,
                    },
                  },
                },
              }}
            >
              {roleOptions.map((option) => (
                <MenuItem
                  key={option.value}
                  value={option.value}
                  sx={{
                    transition: 'all 0.2s',
                    '&:hover': {
                      backgroundColor: 'action.hover',
                    },
                  }}
                >
                  {option.label}
                </MenuItem>
              ))}
            </TextField>
          </Grid>
        </Grid>

        <Box
          sx={{
            mt: 4,
            display: 'flex',
            justifyContent: 'flex-end',
            gap: 2
          }}
        >
          <LoadingButton
            type="submit"
            variant="contained"
            loading={loading}
            sx={{
              minWidth: 100,
              py: 1.2,
              fontSize: '0.9rem',
              transition: 'all 0.2s',
              '&:not(:disabled):hover': {
                transform: 'translateY(-2px)',
                boxShadow: (theme) => theme.shadows[8],
              }
            }}
          >
            {selectedUser ? 'Assign User' : 'Add User to Agency'}
          </LoadingButton>
        </Box>
      </Card>
    </Box>
  );
}