import React, { useState } from 'react';
import {
  Box,
  Typography,
  Paper,
  Button,
  Table,
  TableBody,
  TableCell,
  TableContainer,
  TableHead,
  TableRow,
  TablePagination,
  IconButton,
  Chip,
  Dialog,
  DialogTitle,
  DialogContent,
  DialogActions,
  TextField,
  CircularProgress,
  Alert,
  Menu,
  MenuItem,
  ListItemIcon,
  ListItemText,
  Tooltip,
  Grid,
  InputAdornment,
  FormControl,
  InputLabel,
  Select,
  Breadcrumbs,
  Link
} from '@mui/material';
import {
  Add as AddIcon,
  Delete as DeleteIcon,
  Edit as EditIcon,
  ArrowBack as ArrowBackIcon,
  MoreVert as MoreVertIcon,
  Mail as MailIcon,
  Search as SearchIcon,
  Clear as ClearIcon,
  Block as BlockIcon,
  CheckCircle as CheckCircleIcon
} from '@mui/icons-material';
import { Link as RouterLink, useNavigate, useParams } from 'react-router-dom';
import { format } from 'date-fns';
import { 
  useMailingList, 
  useSubscribers, 
  useAddSubscriber, 
  useUpdateSubscriber, 
  useDeleteSubscriber,
  useSubscriberActivity
} from '@hooks/emailCampaignHooks';

const SubscribersPage = () => {
  const navigate = useNavigate();
  const { listId } = useParams();
  const [searchTerm, setSearchTerm] = useState('');
  const [page, setPage] = useState(0);
  const [rowsPerPage, setRowsPerPage] = useState(25);
  const [statusFilter, setStatusFilter] = useState('all');
  const [selectedSubscriber, setSelectedSubscriber] = useState(null);
  const [anchorEl, setAnchorEl] = useState(null);
  const [addDialogOpen, setAddDialogOpen] = useState(false);
  const [editDialogOpen, setEditDialogOpen] = useState(false);
  const [deleteDialogOpen, setDeleteDialogOpen] = useState(false);
  const [activityDialogOpen, setActivityDialogOpen] = useState(false);
  // New subscriber form data
  const [subscriberForm, setSubscriberForm] = useState({
    email: '',
    firstName: '',
    lastName: '',
    status: 'active'
  });
  
  // Fetch mailing list details
  const { data: mailingList, isLoading: listLoading, error: listError } = useMailingList(listId);
  
  // Fetch subscribers with pagination and filtering
  const { data: subscribersData, isLoading: subscribersLoading, error: subscribersError } = 
    useSubscribers(listId, page, rowsPerPage, searchTerm, statusFilter);
  
  // Fetch subscriber activity when needed
  const { data: subscriberActivity, isLoading: activityLoading } = 
    useSubscriberActivity(selectedSubscriber?.id, activityDialogOpen);
  
  // Mutations
  const addSubscriber = useAddSubscriber();
  const updateSubscriber = useUpdateSubscriber();
  const deleteSubscriber = useDeleteSubscriber();
  
  // Handle form input changes
  const handleFormChange = (e) => {
    const { name, value } = e.target;
    setSubscriberForm(prev => ({ ...prev, [name]: value }));
  };
  
  // Handle search input change
  const handleSearchChange = (e) => {
    setSearchTerm(e.target.value);
    setPage(0); // Reset to first page when searching
  };
  
  // Clear search
  const handleClearSearch = () => {
    setSearchTerm('');
  };
  
  // Handle status filter change
  const handleStatusFilterChange = (e) => {
    setStatusFilter(e.target.value);
    setPage(0); // Reset to first page when changing filter
  };
  
  // Handle page change
  const handleChangePage = (event, newPage) => {
    setPage(newPage);
  };
  
  // Handle rows per page change
  const handleChangeRowsPerPage = (event) => {
    setRowsPerPage(parseInt(event.target.value, 10));
    setPage(0);
  };
  
  // Open menu for a specific subscriber
  const handleMenuOpen = (event, subscriber) => {
    setAnchorEl(event.currentTarget);
    setSelectedSubscriber(subscriber);
  };
  
  // Close menu
  const handleMenuClose = () => {
    setAnchorEl(null);
  };
  
  // Open edit dialog for a subscriber
  const handleEditSubscriber = () => {
    if (!selectedSubscriber) return;
    
    setSubscriberForm({
      email: selectedSubscriber.email,
      firstName: selectedSubscriber.first_name || '',
      lastName: selectedSubscriber.last_name || '',
      status: selectedSubscriber.status
    });
    
    setEditDialogOpen(true);
    handleMenuClose();
  };
  
  // Open delete confirmation dialog
  const handleDeleteClick = () => {
    setDeleteDialogOpen(true);
    handleMenuClose();
  };
  
  // View subscriber activity
  const handleViewActivity = () => {
    setActivityDialogOpen(true);
    handleMenuClose();
  };
  
  // Add new subscriber
  const handleAddSubscriber = async () => {
    if (!subscriberForm.email) return;
    
    try {
      await addSubscriber.mutateAsync({
        listId,
        subscriberData: {
          email: subscriberForm.email,
          firstName: subscriberForm.firstName,
          lastName: subscriberForm.lastName,
          status: subscriberForm.status
        }
      });
      
      // Reset form and close dialog
      setSubscriberForm({
        email: '',
        firstName: '',
        lastName: '',
        status: 'active'
      });
      setAddDialogOpen(false);
    } catch (error) {
      console.error('Failed to add subscriber:', error);
    }
  };
  
  // Update subscriber
  const handleUpdateSubscriber = async () => {
    if (!selectedSubscriber || !subscriberForm.email) return;
    
    try {
      await updateSubscriber.mutateAsync({
        id: selectedSubscriber.id,
        subscriberData: {
          email: subscriberForm.email,
          firstName: subscriberForm.firstName,
          lastName: subscriberForm.lastName,
          status: subscriberForm.status
        }
      });
      
      // Reset form and close dialog
      setEditDialogOpen(false);
    } catch (error) {
      console.error('Failed to update subscriber:', error);
    }
  };
  
  // Delete subscriber
  const handleConfirmDelete = async () => {
    if (!selectedSubscriber) return;
    
    try {
      await deleteSubscriber.mutateAsync(selectedSubscriber.id);
      setDeleteDialogOpen(false);
    } catch (error) {
      console.error('Failed to delete subscriber:', error);
    }
  };
  
  // Format date
  const formatDate = (dateString) => {
    if (!dateString) return '—';
    return format(new Date(dateString), 'MMM d, yyyy h:mm a');
  };
  
  // Get status chip color
  const getStatusColor = (status) => {
    switch (status) {
      case 'active':
        return 'success';
      case 'unsubscribed':
        return 'error';
      case 'bounced':
        return 'warning';
      case 'complained':
        return 'error';
      default:
        return 'default';
    }
  };
  
  // Loading state
  if (listLoading) {
    return <Box sx={{ display: 'flex', justifyContent: 'center', py: 4 }}><CircularProgress /></Box>;
  }
  
  // Error state
  if (listError) {
    return <Alert severity="error" sx={{ my: 2 }}>{listError.message}</Alert>;
  }
  
  return (
    <Box>
      {/* Header with breadcrumbs */}
      <Box mb={3}>
        <Button
          startIcon={<ArrowBackIcon />}
          onClick={() => navigate('/admin/mailing-lists')}
          sx={{ mb: 2 }}
        >
          Back to Mailing Lists
        </Button>
        
        <Breadcrumbs sx={{ mb: 2 }}>
          <Link component={RouterLink} to="/admin" color="inherit">
            Admin
          </Link>
          <Link component={RouterLink} to="/admin/mailing-lists" color="inherit">
            Mailing Lists
          </Link>
          <Typography color="text.primary">Subscribers</Typography>
        </Breadcrumbs>
        
        <Box display="flex" justifyContent="space-between" alignItems="center">
          <Typography variant="h4" component="h1">
            {mailingList?.name} Subscribers
          </Typography>
          <Button
            variant="contained"
            color="primary"
            startIcon={<AddIcon />}
            onClick={() => setAddDialogOpen(true)}
          >
            Add Subscriber
          </Button>
        </Box>
        {mailingList?.description && (
          <Typography variant="body1" color="text.secondary" mt={1}>
            {mailingList.description}
          </Typography>
        )}
      </Box>
      
      {/* Filters and Search */}
      <Paper sx={{ p: 2, mb: 3 }}>
        <Grid container spacing={2} alignItems="center">
          <Grid item xs={12} md={4}>
            <TextField
              fullWidth
              placeholder="Search by email or name..."
              value={searchTerm}
              onChange={handleSearchChange}
              InputProps={{
                startAdornment: (
                  <InputAdornment position="start">
                    <SearchIcon />
                  </InputAdornment>
                ),
                endAdornment: searchTerm && (
                  <InputAdornment position="end">
                    <IconButton 
                      size="small" 
                      onClick={handleClearSearch}
                      aria-label="clear search"
                    >
                      <ClearIcon />
                    </IconButton>
                  </InputAdornment>
                )
              }}
            />
          </Grid>
          <Grid item xs={12} md={3}>
            <FormControl fullWidth>
              <InputLabel id="status-filter-label">Status</InputLabel>
              <Select
                labelId="status-filter-label"
                value={statusFilter}
                label="Status"
                onChange={handleStatusFilterChange}
              >
                <MenuItem value="all">All Statuses</MenuItem>
                <MenuItem value="active">Active</MenuItem>
                <MenuItem value="unsubscribed">Unsubscribed</MenuItem>
                <MenuItem value="bounced">Bounced</MenuItem>
                <MenuItem value="complained">Complained</MenuItem>
              </Select>
            </FormControl>
          </Grid>
          <Grid item xs md={5}>
            <Box display="flex" justifyContent="flex-end" alignItems="center">
              <Typography variant="body2" color="text.secondary" mr={2}>
                {subscribersData?.totalCount || 0} total subscribers
                {statusFilter !== 'all' && subscribersData?.filteredCount !== undefined && (
                  <>, {subscribersData.filteredCount} ${statusFilter}</>
                )}
              </Typography>
            </Box>
          </Grid>
        </Grid>
      </Paper>
      
      {/* Subscribers Table */}
      <TableContainer component={Paper}>
        <Table size="small">
          <TableHead>
            <TableRow>
              <TableCell>Email</TableCell>
              <TableCell>Name</TableCell>
              <TableCell>Status</TableCell>
              <TableCell>Subscribed</TableCell>
              <TableCell>Last Activity</TableCell>
              <TableCell align="right">Actions</TableCell>
            </TableRow>
          </TableHead>
          <TableBody>
            {subscribersLoading ? (
              <TableRow>
                <TableCell colSpan={6} align="center">
                  <CircularProgress size={40} sx={{ my: 3 }} />
                </TableCell>
              </TableRow>
            ) : subscribersData?.subscribers?.length > 0 ? (
              subscribersData.subscribers.map((subscriber) => (
                <TableRow key={subscriber.id}>
                  <TableCell>{subscriber.email}</TableCell>
                  <TableCell>
                    {subscriber.first_name || subscriber.last_name 
                      ? `${subscriber.first_name || ''} ${subscriber.last_name || ''}`.trim() 
                      : '—'}
                  </TableCell>
                  <TableCell>
                    <Chip 
                      label={subscriber.status} 
                      size="small"
                      color={getStatusColor(subscriber.status)}
                    />
                  </TableCell>
                  <TableCell>{formatDate(subscriber.subscribed_at)}</TableCell>
                  <TableCell>
                    {subscriber.last_activity_at 
                      ? formatDate(subscriber.last_activity_at)
                      : 'No activity'}
                  </TableCell>
                  <TableCell align="right">
                    <Tooltip title="Edit">
                      <IconButton 
                        onClick={() => {
                          setSelectedSubscriber(subscriber);
                          handleEditSubscriber();
                        }}
                        size="small"
                      >
                        <EditIcon fontSize="small" />
                      </IconButton>
                    </Tooltip>
                    
                    <IconButton
                      onClick={(e) => handleMenuOpen(e, subscriber)}
                      size="small"
                    >
                      <MoreVertIcon fontSize="small" />
                    </IconButton>
                  </TableCell>
                </TableRow>
              ))
            ) : (
              <TableRow>
                <TableCell colSpan={6} align="center">
                  <Typography variant="body1" py={3}>
                    {searchTerm || statusFilter !== 'all'
                      ? 'No subscribers match your filters.'
                      : 'No subscribers in this list yet. Add your first subscriber to get started.'}
                  </Typography>
                </TableCell>
              </TableRow>
            )}
          </TableBody>
        </Table>
      </TableContainer>
      
      {/* Pagination */}
      {subscribersData && subscribersData.totalCount > 0 && (
        <TablePagination
          component="div"
          count={subscribersData.filteredCount || subscribersData.totalCount}
          page={page}
          onPageChange={handleChangePage}
          rowsPerPage={rowsPerPage}
          onRowsPerPageChange={handleChangeRowsPerPage}
          rowsPerPageOptions={[10, 25, 50, 100]}
        />
      )}
      
      {/* Subscriber Actions Menu */}
      <Menu
        anchorEl={anchorEl}
        open={Boolean(anchorEl)}
        onClose={handleMenuClose}
      >
        <MenuItem onClick={handleViewActivity}>
          <ListItemIcon>
            <MailIcon fontSize="small" />
          </ListItemIcon>
          <ListItemText>View Activity</ListItemText>
        </MenuItem>
        
        {selectedSubscriber && selectedSubscriber.status === 'active' && (
          <MenuItem onClick={() => {
            setSubscriberForm({
              ...subscriberForm,
              email: selectedSubscriber.email,
              firstName: selectedSubscriber.first_name || '',
              lastName: selectedSubscriber.last_name || '',
              status: 'unsubscribed'
            });
            setEditDialogOpen(true);
            handleMenuClose();
          }}>
            <ListItemIcon>
              <BlockIcon fontSize="small" />
            </ListItemIcon>
            <ListItemText>Unsubscribe</ListItemText>
          </MenuItem>
        )}
        
        {selectedSubscriber && selectedSubscriber.status !== 'active' && (
          <MenuItem onClick={() => {
            setSubscriberForm({
              ...subscriberForm,
              email: selectedSubscriber.email,
              firstName: selectedSubscriber.first_name || '',
              lastName: selectedSubscriber.last_name || '',
              status: 'active'
            });
            setEditDialogOpen(true);
            handleMenuClose();
          }}>
            <ListItemIcon>
              <CheckCircleIcon fontSize="small" />
            </ListItemIcon>
            <ListItemText>Reactivate</ListItemText>
          </MenuItem>
        )}
        
        <MenuItem 
          onClick={handleDeleteClick}
          sx={{ color: 'error.main' }}
        >
          <ListItemIcon sx={{ color: 'error.main' }}>
            <DeleteIcon fontSize="small" />
          </ListItemIcon>
          <ListItemText>Delete</ListItemText>
        </MenuItem>
      </Menu>
      
      {/* Add Subscriber Dialog */}
      <Dialog 
        open={addDialogOpen} 
        onClose={() => setAddDialogOpen(false)}
        maxWidth="sm"
        fullWidth
      >
        <DialogTitle>Add New Subscriber</DialogTitle>
        <DialogContent>
          <TextField
            autoFocus
            margin="dense"
            name="email"
            label="Email Address"
            type="email"
            fullWidth
            variant="outlined"
            value={subscriberForm.email}
            onChange={handleFormChange}
            required
            sx={{ mb: 2, mt: 1 }}
          />
          
          <Grid container spacing={2}>
            <Grid item xs={12} sm={6}>
              <TextField
                margin="dense"
                name="firstName"
                label="First Name"
                fullWidth
                variant="outlined"
                value={subscriberForm.firstName}
                onChange={handleFormChange}
              />
            </Grid>
            <Grid item xs={12} sm={6}>
              <TextField
                margin="dense"
                name="lastName"
                label="Last Name"
                fullWidth
                variant="outlined"
                value={subscriberForm.lastName}
                onChange={handleFormChange}
              />
            </Grid>
          </Grid>
          
          <FormControl fullWidth sx={{ mt: 2 }}>
            <InputLabel id="status-label">Status</InputLabel>
            <Select
              labelId="status-label"
              name="status"
              value={subscriberForm.status}
              label="Status"
              onChange={handleFormChange}
            >
              <MenuItem value="active">Active</MenuItem>
              <MenuItem value="unsubscribed">Unsubscribed</MenuItem>
            </Select>
          </FormControl>
          
          {addSubscriber.error && (
            <Alert severity="error" sx={{ mt: 2 }}>
              {addSubscriber.error.message}
            </Alert>
          )}
        </DialogContent>
        <DialogActions>
          <Button onClick={() => setAddDialogOpen(false)}>Cancel</Button>
          <Button 
            onClick={handleAddSubscriber} 
            variant="contained"
            disabled={!subscriberForm.email || addSubscriber.isLoading}
          >
            {addSubscriber.isLoading ? <CircularProgress size={24} /> : 'Add Subscriber'}
          </Button>
        </DialogActions>
      </Dialog>
      
      {/* Edit Subscriber Dialog */}
      <Dialog 
        open={editDialogOpen} 
        onClose={() => setEditDialogOpen(false)}
        maxWidth="sm"
        fullWidth
      >
        <DialogTitle>Edit Subscriber</DialogTitle>
        <DialogContent>
          <TextField
            autoFocus
            margin="dense"
            name="email"
            label="Email Address"
            type="email"
            fullWidth
            variant="outlined"
            value={subscriberForm.email}
            onChange={handleFormChange}
            required
            sx={{ mb: 2, mt: 1 }}
          />
          
          <Grid container spacing={2}>
            <Grid item xs={12} sm={6}>
              <TextField
                margin="dense"
                name="firstName"
                label="First Name"
                fullWidth
                variant="outlined"
                value={subscriberForm.firstName}
                onChange={handleFormChange}
              />
            </Grid>
            <Grid item xs={12} sm={6}>
              <TextField
                margin="dense"
                name="lastName"
                label="Last Name"
                fullWidth
                variant="outlined"
                value={subscriberForm.lastName}
                onChange={handleFormChange}
              />
            </Grid>
          </Grid>
          
          <FormControl fullWidth sx={{ mt: 2 }}>
            <InputLabel id="edit-status-label">Status</InputLabel>
            <Select
              labelId="edit-status-label"
              name="status"
              value={subscriberForm.status}
              label="Status"
              onChange={handleFormChange}
            >
              <MenuItem value="active">Active</MenuItem>
              <MenuItem value="unsubscribed">Unsubscribed</MenuItem>
              <MenuItem value="bounced">Bounced</MenuItem>
              <MenuItem value="complained">Complained</MenuItem>
            </Select>
          </FormControl>
          
          {updateSubscriber.error && (
            <Alert severity="error" sx={{ mt: 2 }}>
              {updateSubscriber.error.message}
            </Alert>
          )}
        </DialogContent>
        <DialogActions>
          <Button onClick={() => setEditDialogOpen(false)}>Cancel</Button>
          <Button 
            onClick={handleUpdateSubscriber} 
            variant="contained"
            disabled={!subscriberForm.email || updateSubscriber.isLoading}
          >
            {updateSubscriber.isLoading ? <CircularProgress size={24} /> : 'Save Changes'}
          </Button>
        </DialogActions>
      </Dialog>
      
      {/* Delete Confirmation Dialog */}
      <Dialog
        open={deleteDialogOpen}
        onClose={() => setDeleteDialogOpen(false)}
      >
        <DialogTitle>Confirm Deletion</DialogTitle>
        <DialogContent>
          <Typography>
            Are you sure you want to delete the subscriber{' '}
            <strong>{selectedSubscriber?.email}</strong>?
            This action cannot be undone.
          </Typography>
        </DialogContent>
        <DialogActions>
          <Button onClick={() => setDeleteDialogOpen(false)}>Cancel</Button>
          <Button 
            onClick={handleConfirmDelete} 
            color="error" 
            variant="contained"
            disabled={deleteSubscriber.isLoading}
          >
            {deleteSubscriber.isLoading ? <CircularProgress size={24} /> : 'Delete'}
          </Button>
        </DialogActions>
      </Dialog>
      
      {/* Activity Dialog */}
      <Dialog
        open={activityDialogOpen}
        onClose={() => setActivityDialogOpen(false)}
        maxWidth="md"
        fullWidth
      >
        <DialogTitle>
          Subscriber Activity
          {selectedSubscriber && (
            <Typography variant="subtitle1" component="div">
              {selectedSubscriber.email}
            </Typography>
          )}
        </DialogTitle>
        <DialogContent>
          {activityLoading ? (
            <Box sx={{ display: 'flex', justifyContent: 'center', py: 4 }}>
              <CircularProgress />
            </Box>
          ) : subscriberActivity && subscriberActivity.length > 0 ? (
            <TableContainer>
              <Table size="small">
                <TableHead>
                  <TableRow>
                    <TableCell>Date</TableCell>
                    <TableCell>Campaign</TableCell>
                    <TableCell>Activity Type</TableCell>
                    <TableCell>Details</TableCell>
                  </TableRow>
                </TableHead>
                <TableBody>
                  {subscriberActivity.map((activity) => (
                    <TableRow key={activity.id}>
                      <TableCell>{formatDate(activity.timestamp)}</TableCell>
                      <TableCell>{activity.campaign_name || '—'}</TableCell>
                      <TableCell>
                        <Chip 
                          label={activity.type} 
                          size="small"
                          color={
                            activity.type === 'open' ? 'info' :
                            activity.type === 'click' ? 'success' :
                            activity.type === 'bounce' ? 'warning' :
                            activity.type === 'complaint' ? 'error' :
                            activity.type === 'unsubscribe' ? 'error' :
                            'default'
                          }
                        />
                      </TableCell>
                      <TableCell>{activity.details || '—'}</TableCell>
                    </TableRow>
                  ))}
                </TableBody>
              </Table>
            </TableContainer>
          ) : (
            <Typography align="center" py={3}>
              No activity recorded for this subscriber.
            </Typography>
          )}
        </DialogContent>
        <DialogActions>
          <Button onClick={() => setActivityDialogOpen(false)}>Close</Button>
        </DialogActions>
      </Dialog>
    </Box>
  );
};

export default SubscribersPage;