import React, { useState } from 'react';
import {
  Box,
  Typography,
  Paper,
  Button,
  Table,
  TableBody,
  TableCell,
  TableContainer,
  TableHead,
  TableRow,
  IconButton,
  Chip,
  Menu,
  MenuItem,
  ListItemIcon,
  ListItemText,
  TextField,
  InputAdornment,
  Tabs,
  Tab,
  CircularProgress,
  Tooltip,
  Alert
} from '@mui/material';
import {
  Add as AddIcon,
  Edit as EditIcon,
  Delete as DeleteIcon,
  MoreVert as MoreVertIcon,
  ContentCopy as DuplicateIcon,
  Archive as ArchiveIcon,
  Send as SendIcon,
  Refresh as RefreshIcon,
  Search as SearchIcon,
  BarChart as AnalyticsIcon,
  Clear as ClearIcon
} from '@mui/icons-material';
import { Link as RouterLink, useNavigate } from 'react-router-dom';
import { format } from 'date-fns';
import { 
  useEmailCampaigns, 
  useDeleteEmailCampaign, 
  useDuplicateEmailCampaign 
} from '../../hooks/emailCampaignHooks';

const EmailCampaignsPage = () => {
  const navigate = useNavigate();
  const [activeTab, setActiveTab] = useState(0);
  const [searchTerm, setSearchTerm] = useState('');
  const [anchorEl, setAnchorEl] = useState(null);
  const [selectedCampaign, setSelectedCampaign] = useState(null);
  
  // Get all campaigns with optional filtering
  const { data: campaigns, isLoading, error, refetch } = useEmailCampaigns(
    activeTab === 0 ? undefined : 
    activeTab === 1 ? 'draft' : 
    activeTab === 2 ? 'scheduled' : 
    activeTab === 3 ? 'sent' : 
    activeTab === 4 ? 'archived' : undefined
  );
  
  // Delete campaign mutation
  const deleteCampaign = useDeleteEmailCampaign();
  
  // Duplicate campaign mutation
  const duplicateCampaign = useDuplicateEmailCampaign();

  // Handle tab change
  const handleTabChange = (event, newValue) => {
    setActiveTab(newValue);
  };
  
  // Handle search input change
  const handleSearchChange = (e) => {
    setSearchTerm(e.target.value);
  };
  
  // Clear search
  const handleClearSearch = () => {
    setSearchTerm('');
  };

  // Handle menu open
  const handleMenuOpen = (event, campaign) => {
    setAnchorEl(event.currentTarget);
    setSelectedCampaign(campaign);
  };

  // Handle menu close
  const handleMenuClose = () => {
    setAnchorEl(null);
    setSelectedCampaign(null);
  };

  // Handle campaign deletion
  const handleDelete = async () => {
    if (selectedCampaign) {
      try {
        await deleteCampaign.mutateAsync(selectedCampaign.id);
        handleMenuClose();
      } catch (error) {
        console.error('Failed to delete campaign:', error);
      }
    }
  };

  // Handle campaign duplication
  const handleDuplicate = async () => {
    if (selectedCampaign) {
      try {
        await duplicateCampaign.mutateAsync(selectedCampaign.id);
        handleMenuClose();
      } catch (error) {
        console.error('Failed to duplicate campaign:', error);
      }
    }
  };

  // Filter campaigns based on search term
  const filteredCampaigns = campaigns 
    ? campaigns.filter(campaign => 
        campaign.name.toLowerCase().includes(searchTerm.toLowerCase()) ||
        campaign.subject.toLowerCase().includes(searchTerm.toLowerCase())
      )
    : [];
  
  // 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 'draft':
        return 'default';
      case 'scheduled':
        return 'warning';
      case 'sending':
        return 'info';
      case 'sent':
        return 'success';
      case 'archived':
        return 'error';
      default:
        return 'default';
    }
  };
  
  // Get status display text
  const getStatusText = (status) => {
    switch (status) {
      case 'draft':
        return 'Draft';
      case 'scheduled':
        return 'Scheduled';
      case 'sending':
        return 'Sending';
      case 'sent':
        return 'Sent';
      case 'archived':
        return 'Archived';
      default:
        return status;
    }
  };

  // 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>
      <Box sx={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', mb: 3 }}>
        <Typography variant="h4" component="h1">
          Email Campaigns
        </Typography>
        
        <Button
          variant="contained"
          color="primary"
          startIcon={<AddIcon />}
          component={RouterLink}
          to="/admin/email-campaigns/new"
        >
          Create Campaign
        </Button>
      </Box>
      
      {/* Tabs for filtering */}
      <Paper sx={{ mb: 3 }}>
        <Tabs
          value={activeTab}
          onChange={handleTabChange}
          indicatorColor="primary"
          textColor="primary"
          variant="scrollable"
          scrollButtons="auto"
        >
          <Tab label="All Campaigns" />
          <Tab label="Drafts" />
          <Tab label="Scheduled" />
          <Tab label="Sent" />
          <Tab label="Archived" />
        </Tabs>
      </Paper>
      
      {/* Search and Actions */}
      <Box sx={{ display: 'flex', mb: 3, gap: 2 }}>
        <TextField
          placeholder="Search campaigns..."
          variant="outlined"
          fullWidth
          size="small"
          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>
            )
          }}
        />
        
        <Button
          variant="outlined"
          startIcon={<RefreshIcon />}
          onClick={() => refetch()}
        >
          Refresh
        </Button>
      </Box>
      
      {/* Campaigns Table */}
      <TableContainer component={Paper}>
        <Table aria-label="email campaigns table">
          <TableHead>
            <TableRow>
              <TableCell>Name</TableCell>
              <TableCell>Subject</TableCell>
              <TableCell>Status</TableCell>
              <TableCell>Recipients</TableCell>
              <TableCell>Created</TableCell>
              <TableCell>Sent/Scheduled</TableCell>
              <TableCell align="right">Actions</TableCell>
            </TableRow>
          </TableHead>
          <TableBody>
            {filteredCampaigns.length > 0 ? (
              filteredCampaigns.map((campaign) => (
                <TableRow key={campaign.id}>
                  <TableCell>{campaign.name}</TableCell>
                  <TableCell>{campaign.subject}</TableCell>
                  <TableCell>
                    <Chip 
                      label={getStatusText(campaign.status)} 
                      color={getStatusColor(campaign.status)}
                      size="small"
                    />
                  </TableCell>
                  <TableCell>
                    {campaign.recipient_count === undefined ? '—' : campaign.recipient_count}
                  </TableCell>
                  <TableCell>{formatDate(campaign.created_at)}</TableCell>
                  <TableCell>
                    {campaign.status === 'sent' 
                      ? formatDate(campaign.sent_at) 
                      : campaign.status === 'scheduled' 
                        ? formatDate(campaign.scheduled_for)
                        : '—'}
                  </TableCell>
                  <TableCell align="right">
                    {['draft', 'scheduled'].includes(campaign.status) && (
                      <Tooltip title="Edit">
                        <IconButton 
                          aria-label="edit campaign"
                          onClick={() => navigate(`/admin/email-campaigns/${campaign.id}`)}
                          size="small"
                        >
                          <EditIcon />
                        </IconButton>
                      </Tooltip>
                    )}
                    
                    {campaign.status === 'draft' && (
                      <Tooltip title="Send">
                        <IconButton 
                          aria-label="send campaign"
                          onClick={() => navigate(`/admin/email-campaigns/${campaign.id}/send`)}
                          size="small"
                          color="primary"
                        >
                          <SendIcon />
                        </IconButton>
                      </Tooltip>
                    )}
                    
                    {['sent', 'scheduled'].includes(campaign.status) && (
                      <Tooltip title="View Analytics">
                        <IconButton 
                          aria-label="campaign analytics"
                          onClick={() => navigate(`/admin/email-campaigns/${campaign.id}/analytics`)}
                          size="small"
                          color="info"
                        >
                          <AnalyticsIcon />
                        </IconButton>
                      </Tooltip>
                    )}
                    
                    <IconButton
                      aria-label="more options"
                      onClick={(e) => handleMenuOpen(e, campaign)}
                      size="small"
                    >
                      <MoreVertIcon />
                    </IconButton>
                  </TableCell>
                </TableRow>
              ))
            ) : (
              <TableRow>
                <TableCell colSpan={7} align="center">
                  <Typography variant="body1" py={3}>
                    {searchTerm 
                      ? 'No campaigns match your search criteria.' 
                      : activeTab !== 0 
                        ? `No ${activeTab === 1 ? 'draft' : activeTab === 2 ? 'scheduled' : activeTab === 3 ? 'sent' : 'archived'} campaigns found.` 
                        : 'No campaigns found. Create your first campaign by clicking the "Create Campaign" button.'}
                  </Typography>
                </TableCell>
              </TableRow>
            )}
          </TableBody>
        </Table>
      </TableContainer>
      
      {/* Campaign Actions Menu */}
      <Menu
        anchorEl={anchorEl}
        open={Boolean(anchorEl)}
        onClose={handleMenuClose}
      >
        <MenuItem onClick={handleDuplicate} disabled={duplicateCampaign.isLoading}>
          <ListItemIcon>
            <DuplicateIcon fontSize="small" />
          </ListItemIcon>
          <ListItemText>Duplicate</ListItemText>
        </MenuItem>
        
        {selectedCampaign && selectedCampaign.status !== 'archived' && (
          <MenuItem onClick={() => {
            // Archive logic would go here
            handleMenuClose();
          }}>
            <ListItemIcon>
              <ArchiveIcon fontSize="small" />
            </ListItemIcon>
            <ListItemText>Archive</ListItemText>
          </MenuItem>
        )}
        
        <MenuItem 
          onClick={handleDelete} 
          disabled={deleteCampaign.isLoading}
          sx={{ color: 'error.main' }}
        >
          <ListItemIcon sx={{ color: 'error.main' }}>
            <DeleteIcon fontSize="small" />
          </ListItemIcon>
          <ListItemText>Delete</ListItemText>
        </MenuItem>
      </Menu>
    </Box>
  );
};

export default EmailCampaignsPage;