import React, { useState } from 'react';
import {
  Box,
  Typography,
  Paper,
  Button,
  Table,
  TableBody,
  TableCell,
  TableContainer,
  TableHead,
  TableRow,
  IconButton,
  Chip,
  Dialog,
  DialogTitle,
  DialogContent,
  DialogActions,
  TextField,
  CircularProgress,
  Alert,
  Tabs,
  Tab,
  Menu,
  MenuItem,
  ListItemIcon,
  ListItemText,
  Tooltip,
  Grid,
  InputAdornment
} from '@mui/material';
import {
  Add as AddIcon,
  Edit as EditIcon,
  Delete as DeleteIcon,
  Download as DownloadIcon,
  Upload as UploadIcon,
  People as PeopleIcon,
  MoreVert as MoreVertIcon,
  Search as SearchIcon,
  Clear as ClearIcon
} from '@mui/icons-material';
import { Link as RouterLink, useNavigate } from 'react-router-dom';
import { format } from 'date-fns';
import { 
  useMailingLists, 
  useCreateMailingList, 
  useUpdateMailingList, 
  useDeleteMailingList,
  useImportSubscribers,
  useExportSubscribers
} from '../../hooks/emailCampaignHooks';

const MailingListsPage = () => {
  const navigate = useNavigate();
  const [searchTerm, setSearchTerm] = useState('');
  const [newListDialogOpen, setNewListDialogOpen] = useState(false);
  const [editListData, setEditListData] = useState(null);
  const [importDialogOpen, setImportDialogOpen] = useState(false);
  const [selectedListId, setSelectedListId] = useState(null);
  const [deleteDialogOpen, setDeleteDialogOpen] = useState(false);
  const [importFile, setImportFile] = useState(null);
  const [anchorEl, setAnchorEl] = useState(null);
  
  // Fetch all mailing lists
  const { data: mailingLists, isLoading, error } = useMailingLists();
  
  // Mutations
  const createList = useCreateMailingList();
  const updateList = useUpdateMailingList();
  const deleteList = useDeleteMailingList();
  const importSubscribers = useImportSubscribers();
  const exportSubscribers = useExportSubscribers();
  
  // New list form state
  const [newListForm, setNewListForm] = useState({
    name: '',
    description: ''
  });
  
  // Handle form input changes
  const handleFormChange = (e) => {
    const { name, value } = e.target;
    setNewListForm(prev => ({ ...prev, [name]: value }));
  };
  
  // Handle edit form input changes
  const handleEditFormChange = (e) => {
    const { name, value } = e.target;
    setEditListData(prev => ({ ...prev, [name]: value }));
  };
  
  // Handle search input change
  const handleSearchChange = (e) => {
    setSearchTerm(e.target.value);
  };
  
  // Clear search
  const handleClearSearch = () => {
    setSearchTerm('');
  };
  
  // Filter lists based on search term
  const filteredLists = mailingLists
    ? mailingLists.filter(list =>
        list.name.toLowerCase().includes(searchTerm.toLowerCase()) ||
        (list.description && list.description.toLowerCase().includes(searchTerm.toLowerCase()))
      )
    : [];
  
  // Format date
  const formatDate = (dateString) => {
    if (!dateString) return '—';
    return format(new Date(dateString), 'MMM d, yyyy');
  };
  
  // Open menu for a specific list
  const handleMenuOpen = (event, listId) => {
    setAnchorEl(event.currentTarget);
    setSelectedListId(listId);
  };
  
  // Close menu
  const handleMenuClose = () => {
    setAnchorEl(null);
    setSelectedListId(null);
  };
  
  // Open edit dialog for a list
  const handleEditList = (list) => {
    setEditListData(list);
    handleMenuClose();
  };
  
  // Open delete confirmation dialog
  const handleDeleteClick = () => {
    setDeleteDialogOpen(true);
    handleMenuClose();
  };
  
  // Confirm list deletion
  const handleConfirmDelete = async () => {
    if (selectedListId) {
      try {
        await deleteList.mutateAsync(selectedListId);
        setDeleteDialogOpen(false);
        setSelectedListId(null);
      } catch (error) {
        console.error('Failed to delete list:', error);
      }
    }
  };
  
  // Handle new list submission
  const handleCreateList = async () => {
    if (!newListForm.name) return;
    
    try {
      await createList.mutateAsync(newListForm);
      setNewListForm({ name: '', description: '' });
      setNewListDialogOpen(false);
    } catch (error) {
      console.error('Failed to create list:', error);
    }
  };
  
  // Handle list update
  const handleUpdateList = async () => {
    if (!editListData || !editListData.id || !editListData.name) return;
    
    try {
      await updateList.mutateAsync({
        id: editListData.id,
        listData: {
          name: editListData.name,
          description: editListData.description
        }
      });
      setEditListData(null);
    } catch (error) {
      console.error('Failed to update list:', error);
    }
  };
  
  // Handle file selection for import
  const handleFileChange = (e) => {
    if (e.target.files && e.target.files.length > 0) {
      setImportFile(e.target.files[0]);
    }
  };
  
  // Handle subscriber import
  const handleImport = async () => {
    if (!importFile || !selectedListId) return;
    
    try {
      const formData = new FormData();
      formData.append('file', importFile);
      formData.append('listId', selectedListId);
      
      await importSubscribers.mutateAsync(formData);
      setImportDialogOpen(false);
      setImportFile(null);
      handleMenuClose();
    } catch (error) {
      console.error('Failed to import subscribers:', error);
    }
  };
  
  // Handle subscriber export
  const handleExport = async () => {
    if (!selectedListId) return;
    
    try {
      await exportSubscribers.mutateAsync(selectedListId);
      handleMenuClose();
    } catch (error) {
      console.error('Failed to export subscribers:', error);
    }
  };
  
  // Loading state
  if (isLoading) {
    return <Box sx={{ display: 'flex', justifyContent: 'center', py: 4 }}><CircularProgress /></Box>;
  }
  
  // Error state
  if (error) {
    return <Alert severity="error" sx={{ my: 2 }}>{error.message}</Alert>;
  }
  return (
    <Box sx={{ p: 3 }}>
      <Typography variant="h4" gutterBottom>
        Mailing Lists
      </Typography>

      <Grid container spacing={2} alignItems="center" sx={{ mb: 2 }}>
        <Grid item xs={12} sm={6}>
          <TextField
            fullWidth
            variant="outlined"
            placeholder="Search mailing lists"
            value={searchTerm}
            onChange={handleSearchChange}
            InputProps={{
              startAdornment: (
                <InputAdornment position="start">
                  <SearchIcon />
                </InputAdornment>
              ),
              endAdornment: searchTerm && (
                <IconButton onClick={handleClearSearch}>
                  <ClearIcon />
                </IconButton>
              )
            }}
          />
        </Grid>
        <Grid item xs={12} sm={6} textAlign="right">
          <Button
            variant="contained"
            startIcon={<AddIcon />}
            onClick={() => setNewListDialogOpen(true)}
          >
            New List
          </Button>
        </Grid>
      </Grid>

      <TableContainer component={Paper}>
        <Table>
          <TableHead>
            <TableRow>
              <TableCell>Name</TableCell>
              <TableCell>Description</TableCell>
              <TableCell>Created</TableCell>
              <TableCell align="right">Actions</TableCell>
            </TableRow>
          </TableHead>
          <TableBody>
            {filteredLists.map((list) => (
              <TableRow key={list.id}>
                <TableCell>{list.name}</TableCell>
                <TableCell>{list.description || '—'}</TableCell>
                <TableCell>{formatDate(list.created_at)}</TableCell>
                <TableCell align="right">
                  <IconButton onClick={(e) => handleMenuOpen(e, list.id)}>
                    <MoreVertIcon />
                  </IconButton>
                  <Menu
                    anchorEl={anchorEl}
                    open={selectedListId === list.id}
                    onClose={handleMenuClose}
                  >
                    <MenuItem onClick={() => handleEditList(list)}>
                      <ListItemIcon><EditIcon fontSize="small" /></ListItemIcon>
                      <ListItemText>Edit</ListItemText>
                    </MenuItem>
                    <MenuItem onClick={handleDeleteClick}>
                      <ListItemIcon><DeleteIcon fontSize="small" /></ListItemIcon>
                      <ListItemText>Delete</ListItemText>
                    </MenuItem>
                    <MenuItem onClick={() => {
                      setImportDialogOpen(true);
                      setSelectedListId(list.id);
                      handleMenuClose();
                    }}>
                      <ListItemIcon><UploadIcon fontSize="small" /></ListItemIcon>
                      <ListItemText>Import Subscribers</ListItemText>
                    </MenuItem>
                    <MenuItem onClick={handleExport}>
                      <ListItemIcon><DownloadIcon fontSize="small" /></ListItemIcon>
                      <ListItemText>Export Subscribers</ListItemText>
                    </MenuItem>
                    <MenuItem onClick={() => navigate(`/admin/mailing-lists/${list.id}/subscribers`)}>
                      <ListItemIcon><PeopleIcon fontSize="small" /></ListItemIcon>
                      <ListItemText>View Subscribers</ListItemText>
                    </MenuItem>
                  </Menu>
                </TableCell>
              </TableRow>
            ))}
          </TableBody>
        </Table>
      </TableContainer>

      {/* New List Dialog */}
      <Dialog open={newListDialogOpen} onClose={() => setNewListDialogOpen(false)}>
        <DialogTitle>Create Mailing List</DialogTitle>
        <DialogContent>
          <TextField
            fullWidth
            label="Name"
            name="name"
            value={newListForm.name}
            onChange={handleFormChange}
            margin="dense"
          />
          <TextField
            fullWidth
            label="Description"
            name="description"
            value={newListForm.description}
            onChange={handleFormChange}
            margin="dense"
            multiline
            rows={3}
          />
        </DialogContent>
        <DialogActions>
          <Button onClick={() => setNewListDialogOpen(false)}>Cancel</Button>
          <Button variant="contained" onClick={handleCreateList}>Create</Button>
        </DialogActions>
      </Dialog>

      {/* Edit List Dialog */}
      <Dialog open={!!editListData} onClose={() => setEditListData(null)}>
        <DialogTitle>Edit Mailing List</DialogTitle>
        <DialogContent>
          <TextField
            fullWidth
            label="Name"
            name="name"
            value={editListData?.name || ''}
            onChange={handleEditFormChange}
            margin="dense"
          />
          <TextField
            fullWidth
            label="Description"
            name="description"
            value={editListData?.description || ''}
            onChange={handleEditFormChange}
            margin="dense"
            multiline
            rows={3}
          />
        </DialogContent>
        <DialogActions>
          <Button onClick={() => setEditListData(null)}>Cancel</Button>
          <Button variant="contained" onClick={handleUpdateList}>Save</Button>
        </DialogActions>
      </Dialog>

      {/* Delete Confirmation Dialog */}
      <Dialog open={deleteDialogOpen} onClose={() => setDeleteDialogOpen(false)}>
        <DialogTitle>Confirm Deletion</DialogTitle>
        <DialogContent>
          Are you sure you want to delete this mailing list?
        </DialogContent>
        <DialogActions>
          <Button onClick={() => setDeleteDialogOpen(false)}>Cancel</Button>
          <Button variant="contained" color="error" onClick={handleConfirmDelete}>Delete</Button>
        </DialogActions>
      </Dialog>

      {/* Import Subscribers Dialog */}
      <Dialog open={importDialogOpen} onClose={() => setImportDialogOpen(false)}>
        <DialogTitle>Import Subscribers</DialogTitle>
        <DialogContent>
          <input type="file" accept=".csv" onChange={handleFileChange} />
        </DialogContent>
        <DialogActions>
          <Button onClick={() => setImportDialogOpen(false)}>Cancel</Button>
          <Button variant="contained" onClick={handleImport}>Import</Button>
        </DialogActions>
      </Dialog>
    </Box>
  );
};

export default MailingListsPage;
