import { useForm } from 'react-hook-form';
import { useState, useEffect } from 'react';
import { Box, Card, Grid, MenuItem, TextField, Typography } from '@mui/material';
import LoadingButton from '@mui/lab/LoadingButton';
import axiosInstance, { axiosInstancee } from '@/utils/axios';
import { useSnackbar } from '@/components/snackbar';
import { useRouter } 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;
};

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

const roles = [
  { 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 { register, handleSubmit, 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);

  // Fetch agencies on component mount
  useEffect(() => {
    const fetchAgencies = async () => {
      try {
        const response = await axiosInstancee.get('/api/user/api/v1/agency/approved');
        setAgencies(response.data);
      } catch (error) {
        console.error('Error fetching agencies:', error);
        enqueueSnackbar('Failed to load agencies', { variant: 'error' });
      }
    };
    fetchAgencies();
  }, [enqueueSnackbar]);

  // Modified search effect to fix the API endpoint URL
  useEffect(() => {
    const debounceTimeout = setTimeout(async () => {
      setIsSearching(true);
      try {
        if (searchQuery.trim().length >= 2) {
          // Fix: Changed the URL structure for the search endpoint
          const response = await axiosInstancee.get('/api/user/search', {
            params: { query: searchQuery }
          });
          setUsers(response.data);
        } else {
          // Show all users when search query is less than 2 characters
          const response = await axiosInstancee.get('/api/user/users');
          setUsers(response.data);
        }
      } catch (error) {
        console.error('Error fetching users:', error);
        enqueueSnackbar('Failed to load users', { variant: 'error' });
      } finally {
        setIsSearching(false);
      }
    }, 500);

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

  const onSubmit = async (data: FormData) => {
    console.log('🚀 Starting submission with data:', data);
    setLoading(true);
    
    try {
      // Step 1: Add user to agency (backend will handle role validation)
      const addMemberResponse = await axiosInstancee.post('/api/user/add/member/agency', null, {
        params: {
          agencyId: data.agencyId,
          userId: data.userId,
          role: data.role,
        },
      });

      // Step 2: Generate Firebase token
      const firebaseToken = await generateToken();
      console.log('🔥 Firebase token generated:', firebaseToken);

      // Step 3: Assign role with Firebase token
      const assignRoleResponse = await axiosInstancee.put(
        `/api/user/assignRoles/${data.userId}`,
        {
          firebaseToken,
          roleNames: [data.role]
        },
        {
          headers: { 'Content-Type': 'application/json' },
        }
      );

      const userEmail = users.find((user) => user.id === data.userId)?.email;  
      if (!userEmail) {
        console.error('❌ User email not found for ID:', data.userId);
        throw new Error('User email not found');
      }
      
      enqueueSnackbar('User added to agency, role assigned, and notification sent successfully!', { variant: 'success' });
      router.push(paths.dashboard.agency.list);

    } catch (error: any) {
      console.error('❌ Error details:', {
        name: error.name,
        message: error.message,
        response: error.response?.data,
        stack: error.stack
      });

      // Handle backend validation errors
      if (error.response?.data === "User has already a role in this agency") {
        enqueueSnackbar('User has already a role in this agency', { 
          variant: 'error',
          autoHideDuration: 3000 
        });
      } else if (error.message === 'User email not found') {
        enqueueSnackbar('Could not find user email', { variant: 'error' });
      } else if (error.response?.status === 400) {
        enqueueSnackbar(error.response.data || 'Invalid request data', { variant: 'error' });
      } else if (error.response?.status === 401) {
        enqueueSnackbar('Authentication error', { variant: 'error' });
      } else if (!error.response && error.message) {
        enqueueSnackbar(`Error: ${error.message}`, { variant: 'error' });
      } else {
        enqueueSnackbar('Failed to add user, assign role, or send notification', { variant: 'error' });
      }
    } finally {
      setLoading(false);
    }
  };

  const filteredAgencies = agencies.filter((agency) => {
    const searchTerm = agencySearchQuery.toLowerCase();
    return agency?.name?.toLowerCase().includes(searchTerm) || 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>
            Add User to Agency
          </Typography>
          <Typography variant="body2" color="text.secondary">
            Search and assign users to your agency with specific roles
          </Typography>
        </Box>

        <Grid container spacing={3}>
          <Grid item xs={12}>
            <TextField
              select
              label="Select Agency"
              fullWidth
              {...register('agencyId', { required: true })}
              InputProps={{
                startAdornment: (
                  <BusinessIcon sx={{ color: 'text.secondary', mr: 1 }} />
                ),
              }}
              sx={{
                '& .MuiOutlinedInput-root': {
                  '&.Mui-focused fieldset': {
                    borderWidth: 2,
                  },
                },
              }}
              SelectProps={{
                MenuProps: {
                  PaperProps: {
                    sx: {
                      maxHeight: 450,
                      '& .MuiMenuItem-root': {
                        px: 2,
                        py: 1,
                        borderRadius: 1,
                        mx: 1,
                        my: 0.5,
                        '&:hover': {
                          backgroundColor: 'action.hover',
                        },
                      },
                    },
                  },
                },
              }}
            >
              <MenuItem>
                <TextField
                  size="small"
                  autoFocus
                  placeholder="Search agency..."
                  fullWidth
                  value={agencySearchQuery}
                  onChange={(e) => {
                    e.stopPropagation();
                    setAgencySearchQuery(e.target.value);
                  }}
                  InputProps={{
                    startAdornment: (
                      <SearchIcon sx={{ color: 'text.secondary', mr: 1 }} />
                    ),
                  }}
                  onClick={(e) => e.stopPropagation()}
                  onKeyDown={(e) => e.stopPropagation()}
                />
              </MenuItem>
              {filteredAgencies.map((agency) => (
                <MenuItem 
                  key={agency.id} 
                  value={agency.id}
                  sx={{
                    transition: 'all 0.2s',
                    '&:hover': {
                      backgroundColor: 'action.hover',
                    },
                  }}
                >
                  {agency.name}
                </MenuItem>
              ))}
            </TextField>
          </Grid>

          <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
              {...register('role', { required: true })}
              InputProps={{
                startAdornment: (
                  <AdminPanelSettingsIcon sx={{ color: 'text.secondary', mr: 1 }} />
                ),
              }}
            >
              {roles.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],
              }
            }}
          >
            Add User to Agency
          </LoadingButton>
        </Box>
      </Card>
    </Box>
  );
}