import React, { useState } from 'react';
import {
  Box,
  Typography,
  Paper,
  Grid,
  Card,
  CardContent,
  Divider,
  Tabs,
  Tab,
  Table,
  TableBody,
  TableCell,
  TableContainer,
  TableHead,
  TableRow,
  TablePagination,
  CircularProgress,
  Alert,
  Button,
  IconButton,
  List,
  ListItem,
  ListItemText,
  ListItemIcon,
  Tooltip,
  Chip,
  TextField,
  InputAdornment,
  Menu,
  MenuItem,
  Breadcrumbs,
  Link
} from '@mui/material';
import {
  ArrowBack as ArrowBackIcon,
  FileDownload as DownloadIcon,
  ContentCopy as CopyIcon,
  Search as SearchIcon,
  Clear as ClearIcon,
  FilterList as FilterIcon,
  MoreVert as MoreVertIcon
} from '@mui/icons-material';
import { Link as RouterLink, useNavigate, useParams } from 'react-router-dom';
import { format } from 'date-fns';
import { 
  useEmailCampaign, 
  useCampaignAnalytics,
  useCampaignSubscriberActivity,
  useExportCampaignReport
} from '../../hooks/emailCampaignHooks';

// Import chart components
import { 
  LineChart, 
  Line, 
  BarChart, 
  Bar, 
  PieChart, 
  Pie, 
  ResponsiveContainer, 
  XAxis, 
  YAxis, 
  Tooltip as RechartsTooltip,
  Cell, 
  Legend 
} from 'recharts';

const CampaignAnalyticsPage = () => {
  const navigate = useNavigate();
  const { id } = useParams();
  const [tabValue, setTabValue] = useState(0);
  const [searchTerm, setSearchTerm] = useState('');
  const [page, setPage] = useState(0);
  const [rowsPerPage, setRowsPerPage] = useState(25);
  const [filterAnchorEl, setFilterAnchorEl] = useState(null);
  const [activityTypeFilter, setActivityTypeFilter] = useState('all');
  const [timePeriod, setTimePeriod] = useState('all');
  
  // Fetch campaign data
  const { data: campaign, isLoading: campaignLoading, error: campaignError } = useEmailCampaign(id);
  
  // Fetch analytics data
  const { data: analytics, isLoading: analyticsLoading, error: analyticsError } = useCampaignAnalytics(id);
  
  // Fetch subscriber activity data with pagination
  const { 
    data: activityData, 
    isLoading: activityLoading,
    error: activityError
  } = useCampaignSubscriberActivity(
    id, page, rowsPerPage, searchTerm, activityTypeFilter, tabValue
  );
  
  // Export report mutation
  const exportReport = useExportCampaignReport();
  
  // Handle tab change
  const handleTabChange = (event, newValue) => {
    setTabValue(newValue);
  };
  
  // Handle search input change
  const handleSearchChange = (e) => {
    setSearchTerm(e.target.value);
    setPage(0); // Reset page when search term changes
  };
  
  // Clear search
  const handleClearSearch = () => {
    setSearchTerm('');
  };
  
  // Handle page change
  const handleChangePage = (event, newValue) => {
    setPage(newValue);
  };
  
  // Handle rows per page change
  const handleChangeRowsPerPage = (event) => {
    setRowsPerPage(parseInt(event.target.value, 10));
    setPage(0);
  };
  
  // Handle filter menu
  const handleFilterClick = (event) => {
    setFilterAnchorEl(event.currentTarget);
  };
  
  const handleFilterClose = () => {
    setFilterAnchorEl(null);
  };
  
  const handleFilterSelect = (filterType) => {
    setActivityTypeFilter(filterType);
    setFilterAnchorEl(null);
    setPage(0); // Reset page when filter changes
  };
  
  // Handle time period change
  const handleTimePeriodChange = (period) => {
    setTimePeriod(period);
  };
  
  // Export campaign report
  const handleExportReport = async () => {
    try {
      await exportReport.mutateAsync(id);
    } catch (error) {
      console.error('Failed to export report:', error);
    }
  };
  
  // Format date
  const formatDate = (dateString) => {
    if (!dateString) return '-';
    return format(new Date(dateString), 'MMM d, yyyy h:mm a');
  };
  
  // Loading state
  if (campaignLoading || analyticsLoading) {
    return <Box sx={{ display: 'flex', justifyContent: 'center', py: 4 }}><CircularProgress /></Box>;
  }
  
  // Error state
  if (campaignError || analyticsError) {
    return <Alert severity="error" sx={{ my: 2 }}>{campaignError?.message || analyticsError?.message}</Alert>;
  }
  
  // Campaign not found
  if (!campaign) {
    return (
      <Alert severity="warning" sx={{ my: 2 }}>
        Campaign not found. Please select a valid campaign.
      </Alert>
    );
  }
  
  // Color constants for charts
  const COLORS = ['#0088FE', '#00C49F', '#FFBB28', '#FF8042', '#A4DE6C'];
  
  // Calculate metrics for display
  const openRate = analytics?.delivered > 0 
    ? ((analytics.opened / analytics.delivered) * 100).toFixed(2) 
    : '0';
    
  const clickRate = analytics?.opened > 0 
    ? ((analytics.clicked / analytics.opened) * 100).toFixed(2) 
    : '0';
    
  const bounceRate = analytics?.sent > 0 
    ? ((analytics.bounced / analytics.sent) * 100).toFixed(2) 
    : '0';
    
  const unsubscribeRate = analytics?.delivered > 0 
    ? ((analytics.unsubscribed / analytics.delivered) * 100).toFixed(2) 
    : '0';
  
  // Generate data for pie chart
  const deliveryPieData = [
    { name: 'Delivered', value: analytics?.delivered || 0 },
    { name: 'Bounced', value: analytics?.bounced || 0 },
  ];
  
  // Generate data for engagement pie chart
  const engagementPieData = [
    { name: 'Opened', value: analytics?.opened || 0 },
    { name: 'Clicked', value: analytics?.clicked || 0 },
    { name: 'Unopened', value: (analytics?.delivered || 0) - (analytics?.opened || 0) },
  ];
  
  const opensByHourData = analytics?.opens_by_hour || [];
  
  return (
    <Box>
      {/* Header with breadcrumbs and back button */}
      <Box mb={3}>
        <Button
          startIcon={<ArrowBackIcon />}
          onClick={() => navigate('/admin/email-campaigns')}
          sx={{ mb: 2 }}
        >
          Back to Campaigns
        </Button>
        
        <Breadcrumbs sx={{ mb: 2 }}>
          <Link component={RouterLink} to="/admin" color="inherit">
            Admin
          </Link>
          <Link component={RouterLink} to="/admin/email-campaigns" color="inherit">
            Email Campaigns
          </Link>
          <Typography color="text.primary">Analytics</Typography>
        </Breadcrumbs>
        
        <Box display="flex" justifyContent="space-between" alignItems="center">
          <Typography variant="h4" component="h1">
            Campaign Analytics: {campaign.name}
          </Typography>
          
          <Button
            variant="outlined"
            startIcon={<DownloadIcon />}
            onClick={handleExportReport}
            disabled={exportReport.isLoading}
          >
            {exportReport.isLoading ? <CircularProgress size={24} /> : 'Export Report'}
          </Button>
        </Box>
      </Box>
      
      {/* Campaign info card */}
      <Paper sx={{ p: 3, mb: 3 }}>
        <Grid container spacing={3}>
          <Grid item xs={12} sm={6} md={4}>
            <Typography variant="subtitle2" color="text.secondary">Subject:</Typography>
            <Typography variant="body1" gutterBottom>{campaign.subject}</Typography>
          </Grid>
          
          <Grid item xs={12} sm={6} md={4}>
            <Typography variant="subtitle2" color="text.secondary">Sent From:</Typography>
            <Typography variant="body1" gutterBottom>
              {campaign.from_name} ({campaign.from_email})
            </Typography>
          </Grid>
          
          <Grid item xs={12} sm={6} md={4}>
            <Typography variant="subtitle2" color="text.secondary">Sent Date:</Typography>
            <Typography variant="body1" gutterBottom>
              {formatDate(campaign.sent_at)}
            </Typography>
          </Grid>
          
          <Grid item xs={12} sm={6} md={4}>
            <Typography variant="subtitle2" color="text.secondary">Status:</Typography>
            <Chip 
              label={campaign.status} 
              color={
                campaign.status === 'draft' ? 'default' :
                campaign.status === 'scheduled' ? 'warning' :
                campaign.status === 'sending' ? 'info' :
                campaign.status === 'sent' ? 'success' :
                'default'
              }
              size="small"
            />
          </Grid>
          
          <Grid item xs={12} sm={6} md={4}>
            <Typography variant="subtitle2" color="text.secondary">Recipients:</Typography>
            <Typography variant="body1" gutterBottom>
              {analytics?.sent || 0} subscribers
            </Typography>
          </Grid>
          
          <Grid item xs={12} sm={6} md={4}>
            <Typography variant="subtitle2" color="text.secondary">List:</Typography>
            <Typography variant="body1" gutterBottom>
              {campaign.list_name || 'Multiple Lists'}
            </Typography>
          </Grid>
        </Grid>
      </Paper>
      
      {/* Key metrics cards */}
      <Grid container spacing={3} sx={{ mb: 3 }}>
        <Grid item xs={6} sm={3}>
          <Card>
            <CardContent>
              <Typography variant="subtitle2" color="text.secondary" gutterBottom>
                Open Rate
              </Typography>
              <Typography variant="h4" component="div" color="primary">
                {openRate}%
              </Typography>
              <Typography variant="body2" color="text.secondary">
                {analytics?.opened || 0} of {analytics?.delivered || 0} delivered
              </Typography>
            </CardContent>
          </Card>
        </Grid>
        
        <Grid item xs={6} sm={3}>
          <Card>
            <CardContent>
              <Typography variant="subtitle2" color="text.secondary" gutterBottom>
                Click Rate
              </Typography>
              <Typography variant="h4" component="div" color="primary">
                {clickRate}%
              </Typography>
              <Typography variant="body2" color="text.secondary">
                {analytics?.clicked || 0} of {analytics?.opened || 0} opened
              </Typography>
            </CardContent>
          </Card>
        </Grid>
        
        <Grid item xs={6} sm={3}>
          <Card>
            <CardContent>
              <Typography variant="subtitle2" color="text.secondary" gutterBottom>
                Bounce Rate
              </Typography>
              <Typography variant="h4" component="div" color={bounceRate > 5 ? "error" : "primary"}>
                {bounceRate}%
              </Typography>
              <Typography variant="body2" color="text.secondary">
                {analytics?.bounced || 0} of {analytics?.sent || 0} sent
              </Typography>
            </CardContent>
          </Card>
        </Grid>
        
        <Grid item xs={6} sm={3}>
          <Card>
            <CardContent>
              <Typography variant="subtitle2" color="text.secondary" gutterBottom>
                Unsubscribe Rate
              </Typography>
              <Typography variant="h4" component="div" color="primary">
                {unsubscribeRate}%
              </Typography>
              <Typography variant="body2" color="text.secondary">
                {analytics?.unsubscribed || 0} of {analytics?.delivered || 0} delivered
              </Typography>
            </CardContent>
          </Card>
        </Grid>
      </Grid>
      
      {/* Tabs for different data views */}
      <Paper sx={{ mb: 3 }}>
        <Tabs
          value={tabValue}
          onChange={handleTabChange}
          indicatorColor="primary"
          textColor="primary"
          variant="fullWidth"
        >
          <Tab label="Overview" />
          <Tab label="Link Performance" />
          <Tab label="Subscriber Activity" />
        </Tabs>
      </Paper>
      
      {/* Tab Content */}
      {/* Overview Tab */}
      {tabValue === 0 && (
        <Grid container spacing={3}>
          {/* Time series chart - opens over time */}
          <Grid item xs={12} md={8}>
            <Paper sx={{ p: 2, height: '100%' }}>
              <Typography variant="subtitle1" gutterBottom>Opens Over Time</Typography>
              
              <Box sx={{ mb: 2 }}>
                <Button 
                  size="small" 
                  variant={timePeriod === 'all' ? 'contained' : 'outlined'} 
                  onClick={() => handleTimePeriodChange('all')}
                  sx={{ mr: 1 }}
                >
                  All
                </Button>
                <Button 
                  size="small" 
                  variant={timePeriod === '24h' ? 'contained' : 'outlined'} 
                  onClick={() => handleTimePeriodChange('24h')}
                  sx={{ mr: 1 }}
                >
                  24 Hours
                </Button>
                <Button 
                  size="small" 
                  variant={timePeriod === '7d' ? 'contained' : 'outlined'} 
                  onClick={() => handleTimePeriodChange('7d')}
                >
                  7 Days
                </Button>
              </Box>
              
              <Box sx={{ height: 300 }}>
                <ResponsiveContainer width="100%" height="100%">
                  <LineChart
                    data={opensByHourData}
                    margin={{ top: 10, right: 30, left: 0, bottom: 0 }}
                  >
                    <XAxis 
                      dataKey="hour" 
                      tickFormatter={(value) => {
                        const date = new Date(value);
                        return format(date, 'h aaa');
                      }}
                    />
                    <YAxis />
                    <RechartsTooltip 
                      formatter={(value, name) => [value, 'Opens']}
                      labelFormatter={(label) => format(new Date(label), 'MMM dd, yyyy h:mm a')}
                    />
                    <Line 
                      type="monotone" 
                      dataKey="opens" 
                      stroke="#8884d8" 
                      activeDot={{ r: 8 }} 
                    />
                  </LineChart>
                </ResponsiveContainer>
              </Box>
            </Paper>
          </Grid>
          
          {/* Pie charts for Delivery and Engagement */}
          <Grid item xs={12} md={4}>
            <Paper sx={{ p: 2, height: '100%' }}>
              <Typography variant="subtitle1" gutterBottom>Delivery</Typography>
              <Box sx={{ height: 160, mb: 3 }}>
                <ResponsiveContainer width="100%" height="100%">
                  <PieChart>
                    <Pie
                      data={deliveryPieData}
                      cx="50%"
                      cy="50%"
                      innerRadius={50}
                      outerRadius={70}
                      fill="#8884d8"
                      paddingAngle={2}
                      dataKey="value"
                      label={({ name, percent }) => `${name} ${(percent * 100).toFixed(0)}%`}
                    >
                      {deliveryPieData.map((entry, index) => (
                        <Cell key={`cell-${index}`} fill={COLORS[index % COLORS.length]} />
                      ))}
                    </Pie>
                    <RechartsTooltip />
                  </PieChart>
                </ResponsiveContainer>
              </Box>
              
              <Divider sx={{ my: 2 }} />
              
              <Typography variant="subtitle1" gutterBottom>Engagement</Typography>
              <Box sx={{ height: 160 }}>
                <ResponsiveContainer width="100%" height="100%">
                  <PieChart>
                    <Pie
                      data={engagementPieData}
                      cx="50%"
                      cy="50%"
                      innerRadius={50}
                      outerRadius={70}
                      fill="#8884d8"
                      paddingAngle={2}
                      dataKey="value"
                      label={({ name, percent }) => `${name} ${(percent * 100).toFixed(0)}%`}
                    >
                      {engagementPieData.map((entry, index) => (
                        <Cell key={`cell-${index}`} fill={COLORS[index % COLORS.length]} />
                      ))}
                    </Pie>
                    <RechartsTooltip />
                  </PieChart>
                </ResponsiveContainer>
              </Box>
            </Paper>
          </Grid>
        </Grid>
      )}
      
      {/* Link Performance Tab */}
      {tabValue === 1 && (
        <Paper sx={{ p: 3 }}>
          <Typography variant="subtitle1" gutterBottom>Link Performance</Typography>
          
          {analytics?.links && analytics.links.length > 0 ? (
            <TableContainer>
              <Table>
                <TableHead>
                  <TableRow>
                    <TableCell>URL</TableCell>
                    <TableCell>Link Text</TableCell>
                    <TableCell align="right">Clicks</TableCell>
                    <TableCell align="right">Unique Clicks</TableCell>
                    <TableCell align="right">Click Rate</TableCell>
                    <TableCell align="right">Actions</TableCell>
                  </TableRow>
                </TableHead>
                <TableBody>
                  {analytics.links.map((link) => (
                    <TableRow key={link.id}>
                      <TableCell>
                        <Typography 
                          variant="body2" 
                          sx={{ 
                            maxWidth: '250px', 
                            overflow: 'hidden', 
                            textOverflow: 'ellipsis',
                            whiteSpace: 'nowrap' 
                          }}
                        >
                          {link.url}
                        </Typography>
                      </TableCell>
                      <TableCell>{link.text || '-'}</TableCell>
                      <TableCell align="right">{link.clicks}</TableCell>
                      <TableCell align="right">{link.unique_clicks}</TableCell>
                      <TableCell align="right">
                        {analytics.opened > 0 
                          ? ((link.unique_clicks / analytics.opened) * 100).toFixed(2) 
                          : '0'}%
                      </TableCell>
                      <TableCell align="right">
                        <Tooltip title="Copy URL">
                          <IconButton 
                            size="small"
                            onClick={() => navigator.clipboard.writeText(link.url)}
                          >
                            <CopyIcon fontSize="small" />
                          </IconButton>
                        </Tooltip>
                      </TableCell>
                    </TableRow>
                  ))}
                </TableBody>
              </Table>
            </TableContainer>
          ) : (
            <Alert severity="info">
              No link data available for this campaign.
            </Alert>
          )}
        </Paper>
      )}
      
      {/* Subscriber Activity Tab */}
      {tabValue === 2 && (
        <Paper sx={{ p: 3 }}>
          <Typography variant="subtitle1" gutterBottom>Subscriber Activity</Typography>
          
          <Box sx={{ mb: 3, display: 'flex', gap: 2 }}>
            <TextField
              placeholder="Search by email or name..."
              variant="outlined"
              size="small"
              fullWidth
              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
              startIcon={<FilterIcon />}
              variant="outlined"
              onClick={handleFilterClick}
              size="small"
            >
              Filter
            </Button>
          </Box>
          
          {/* Activity Type Filter Menu */}
          <Menu
            anchorEl={filterAnchorEl}
            open={Boolean(filterAnchorEl)}
            onClose={handleFilterClose}
          >
            <MenuItem onClick={() => handleFilterSelect('all')}>
              All Activities
            </MenuItem>
            <MenuItem onClick={() => handleFilterSelect('open')}>
              Opens
            </MenuItem>
            <MenuItem onClick={() => handleFilterSelect('click')}>
              Clicks
            </MenuItem>
            <MenuItem onClick={() => handleFilterSelect('bounce')}>
              Bounces
            </MenuItem>
            <MenuItem onClick={() => handleFilterSelect('unsubscribe')}>
              Unsubscribes
            </MenuItem>
          </Menu>
          
          {/* Activity Table */}
          {activityLoading ? (
            <Box sx={{ display: 'flex', justifyContent: 'center', py: 3 }}>
              <CircularProgress />
            </Box>
          ) : activityData?.activities && activityData.activities.length > 0 ? (
            <>
              <TableContainer>
                <Table size="small">
                  <TableHead>
                    <TableRow>
                      <TableCell>Email</TableCell>
                      <TableCell>Name</TableCell>
                      <TableCell>Activity</TableCell>
                      <TableCell>Timestamp</TableCell>
                      <TableCell>Details</TableCell>
                    </TableRow>
                  </TableHead>
                  <TableBody>
                    {activityData.activities.map((activity) => (
                      <TableRow key={activity.id}>
                        <TableCell>{activity.email}</TableCell>
                        <TableCell>
                          {activity.first_name || activity.last_name
                            ? `${activity.first_name || ''} ${activity.last_name || ''}`.trim()
                            : '-'}
                        </TableCell>
                        <TableCell>
                          <Chip 
                            label={activity.type} 
                            size="small"
                            color={
                              activity.type === 'open' ? 'info' :
                              activity.type === 'click' ? 'success' :
                              activity.type === 'bounce' ? 'warning' :
                              activity.type === 'unsubscribe' ? 'error' :
                              'default'
                            }
                          />
                        </TableCell>
                        <TableCell>{formatDate(activity.timestamp)}</TableCell>
                        <TableCell>
                          <Typography variant="body2">
                            {activity.type === 'click'
                              ? `Clicked: ${activity.url || 'Unknown URL'}`
                              : activity.type === 'bounce'
                                ? `Bounce type: ${activity.bounce_type || 'Unknown'}`
                                : activity.details || '-'}
                          </Typography>
                        </TableCell>
                      </TableRow>
                    ))}
                  </TableBody>
                </Table>
              </TableContainer>
              
              <TablePagination
                component="div"
                count={activityData.totalCount || 0}
                page={page}
                onPageChange={handleChangePage}
                rowsPerPage={rowsPerPage}
                onRowsPerPageChange={handleChangeRowsPerPage}
                rowsPerPageOptions={[25, 50, 100]}
              />
            </>
          ) : (
            <Alert severity="info">
              No activity data available for this campaign{searchTerm ? ' matching your search criteria' : ''}.
            </Alert>
          )}
        </Paper>
      )}
    </Box>
  );
};

export default CampaignAnalyticsPage;