import React, { useState, useEffect, useRef } from 'react';
import { 
  Box, 
  Typography, 
  Paper, 
  TextField, 
  Button, 
  Grid, 
  Divider, 
  CircularProgress, 
  Alert, 
  IconButton, 
  Dialog, 
  DialogTitle, 
  DialogContent, 
  DialogActions, 
  FormControl,
  InputLabel,
  Select,
  MenuItem,
  FormHelperText,
  Chip,
  Tooltip
} from '@mui/material';
import { 
  ArrowBack as ArrowBackIcon,
  Send as SendIcon, 
  Save as SaveIcon, 
  Visibility as PreviewIcon,
  PersonAdd as PersonAddIcon,
  People as PeopleIcon,
  Tune as TuneIcon
} from '@mui/icons-material';
import EmailEditor from 'react-email-editor';
import { useNavigate, useParams } from 'react-router-dom';
import { useCreateEmailCampaign, useUpdateEmailCampaign, useEmailCampaign, useMailingLists } from '@hooks/emailCampaignHooks';

const EmailCampaignEditor = () => {
  const { id } = useParams();
  const isNewCampaign = !id;
  const navigate = useNavigate();
  const emailEditorRef = useRef(null);
  
  const [formData, setFormData] = useState({
    name: '',
    subject: '',
    preheader: '',
    fromName: '',
    fromEmail: '',
    content: '',
    design: null,
    listIds: [],
    status: 'draft',
  });
  
  const [previewDialogOpen, setPreviewDialogOpen] = useState(false);
  const [previewContent, setPreviewContent] = useState('');
  const [segmentDialogOpen, setSegmentDialogOpen] = useState(false);
  
  // Fetch email campaign data if editing existing campaign
  const { data: campaign, isLoading: campaignLoading, error: campaignError } = useEmailCampaign(
    isNewCampaign ? null : id
  );
  
  // Fetch available mailing lists
  const { data: mailingLists, isLoading: listsLoading } = useMailingLists();
  
  // Mutation hooks for creating and updating campaigns
  const createCampaign = useCreateEmailCampaign();
  const updateCampaign = useUpdateEmailCampaign();

  // Load campaign data into form when available
  useEffect(() => {
    if (campaign && !isNewCampaign) {
      setFormData({
        name: campaign.name || '',
        subject: campaign.subject || '',
        preheader: campaign.preheader || '',
        fromName: campaign.from_name || '',
        fromEmail: campaign.from_email || '',
        content: campaign.content || '',
        design: campaign.design || null,
        listIds: campaign.list_ids || [],
        status: campaign.status || 'draft',
      });
      
      // Load the design into the editor if it exists
      if (campaign.design && emailEditorRef.current) {
        setTimeout(() => {
          emailEditorRef.current.editor.loadDesign(JSON.parse(campaign.design));
        }, 500);
      }
    }
  }, [campaign, isNewCampaign]);

  const handleInputChange = (e) => {
    const { name, value } = e.target;
    setFormData(prev => ({ ...prev, [name]: value }));
  };
  
  const handleListChange = (event) => {
    setFormData(prev => ({ ...prev, listIds: event.target.value }));
  };

  const onEditorReady = () => {
    // If there's a design being edited, load it
    if (formData.design && emailEditorRef.current) {
      try {
        emailEditorRef.current.editor.loadDesign(
          typeof formData.design === 'string' ? JSON.parse(formData.design) : formData.design
        );
      } catch (error) {
        console.error("Error loading design:", error);
      }
    } 
    // Otherwise load a default template
    else if (emailEditorRef.current) {
      emailEditorRef.current.editor.loadDesign({
        body: {
          rows: [
            {
              cells: [1],
              columns: [
                {
                  contents: [
                    {
                      type: "text",
                      values: {
                        containerPadding: "20px",
                        textAlign: "center",
                        text: `<h1>Your Email Campaign</h1>
                               <p>Start editing this template to create your campaign.</p>`
                      }
                    }
                  ]
                }
              ]
            }
          ]
        }
      });
    }
  };

  const handlePreview = () => {
    if (emailEditorRef.current) {
      emailEditorRef.current.editor.exportHtml((data) => {
        const { html } = data;
        setPreviewContent(`
          <div style="max-width:600px;margin:0 auto;border:1px solid #ccc">
            <div style="padding:10px;background:#f5f5f5;font-weight:bold">Subject: ${formData.subject}</div>
            ${html}
          </div>
        `);
        setPreviewDialogOpen(true);
      });
    }
  };

  const handleSave = async (saveAndExit = false) => {
    if (!emailEditorRef.current) return;
    
    try {
      // Extract the design and HTML content from the editor
      await emailEditorRef.current.editor.exportHtml(async (data) => {
        const { design, html } = data;
        
        // Prepare campaign data
        const campaignData = {
          ...formData,
          content: html,
          design: JSON.stringify(design)
        };
        if (isNewCampaign) {
          // Create new campaign
          await createCampaign.mutateAsync(campaignData);
          if (saveAndExit) {
            navigate('/admin/email-campaigns');
          }else {
            navigate(`/admin/email-campaigns/${id || 'new'}/send`);
          }
        } else {
          // Update existing campaign
          await updateCampaign.mutateAsync({ id, campaignData });
          if (saveAndExit) {
            navigate('/admin/email-campaigns');
          }else {
            navigate(`/admin/email-campaigns/${id || 'new'}/send`);
          }
        }
      });
    } catch (error) {
      console.error('Failed to save campaign:', error);
    }
  };

  const handleSendCampaign = () => {
    handleSave(false)
  }

  if (campaignLoading && !isNewCampaign) {
    return <Box textAlign="center" py={5}><CircularProgress /></Box>;
  }

  if (campaignError && !isNewCampaign) {
    return <Alert severity="error">Error loading campaign: {campaignError.message}</Alert>;
  }

  // Calculate selected lists for display
  const selectedLists = mailingLists 
    ? mailingLists.filter(list => formData.listIds.includes(list.id)) 
    : [];

  return (
    <Box>
      {/* Header with back button */}
      <Box mb={3} display="flex" alignItems="center">
        <IconButton onClick={() => navigate('/admin/email-campaigns')} sx={{ mr: 1 }}>
          <ArrowBackIcon />
        </IconButton>
        <Typography variant="h4">
          {isNewCampaign ? 'Create New Campaign' : 'Edit Campaign'}
        </Typography>
      </Box>

      {/* Main campaign editor form */}
      <Paper sx={{ p: 3, mb: 3 }}>
        <Grid container spacing={3}>
          <Grid item xs={12} md={8}>
            <TextField
              fullWidth
              label="Campaign Name"
              name="name"
              value={formData.name}
              onChange={handleInputChange}
              required
              helperText="Internal name for this campaign (not shown to recipients)"
            />
          </Grid>
          
          <Grid item xs={12} md={4}>
            <FormControl fullWidth>
              <InputLabel id="status-label">Status</InputLabel>
              <Select
                labelId="status-label"
                name="status"
                value={formData.status}
                onChange={handleInputChange}
                label="Status"
              >
                <MenuItem value="draft">Draft</MenuItem>
                <MenuItem value="scheduled">Scheduled</MenuItem>
                <MenuItem value="sent">Sent</MenuItem>
                <MenuItem value="archived">Archived</MenuItem>
              </Select>
            </FormControl>
          </Grid>
          
          <Grid item xs={12} md={6}>
            <TextField
              fullWidth
              label="From Name"
              name="fromName"
              value={formData.fromName}
              onChange={handleInputChange}
              required
              helperText="Name displayed in the 'From' field"
            />
          </Grid>
          
          <Grid item xs={12} md={6}>
            <TextField
              fullWidth
              label="From Email"
              name="fromEmail"
              value={formData.fromEmail}
              onChange={handleInputChange}
              required
              type="email"
              helperText="Email address displayed in the 'From' field"
            />
          </Grid>
          
          <Grid item xs={12}>
            <TextField
              fullWidth
              label="Subject Line"
              name="subject"
              value={formData.subject}
              onChange={handleInputChange}
              required
              helperText="Compelling subject lines often have higher open rates"
            />
          </Grid>
          
          <Grid item xs={12}>
            <TextField
              fullWidth
              label="Preheader Text"
              name="preheader"
              value={formData.preheader}
              onChange={handleInputChange}
              helperText="Text shown in email clients after the subject line (preview text)"
            />
          </Grid>
          
          <Grid item xs={12}>
            <Box mb={1} display="flex" justifyContent="space-between" alignItems="center">
              <Typography variant="subtitle1">Target Audience</Typography>
              <Button 
                startIcon={<TuneIcon />} 
                onClick={() => setSegmentDialogOpen(true)}
                size="small"
              >
                Configure Segments
              </Button>
            </Box>
            
            <FormControl fullWidth>
              <InputLabel id="lists-label">Mailing Lists</InputLabel>
              <Select
                labelId="lists-label"
                multiple
                value={formData.listIds}
                onChange={handleListChange}
                renderValue={(selected) => (
                  <Box sx={{ display: 'flex', flexWrap: 'wrap', gap: 0.5 }}>
                    {selectedLists.map((list) => (
                      <Chip key={list.id} label={`${list.name} (${list.subscriber_count || 0})`} />
                    ))}
                  </Box>
                )}
              >
                {listsLoading ? (
                  <MenuItem disabled>Loading lists...</MenuItem>
                ) : (
                  mailingLists?.map((list) => (
                    <MenuItem key={list.id} value={list.id}>
                      {list.name} ({list.subscriber_count || 0} subscribers)
                    </MenuItem>
                  ))
                )}
              </Select>
              <FormHelperText>
                Select one or more mailing lists to send this campaign to
              </FormHelperText>
            </FormControl>
          </Grid>
        </Grid>
      </Paper>

      {/* Email Content Editor */}
      <Paper sx={{ p: 3, mb: 3 }}>
        <Typography variant="h6" gutterBottom>
          Email Content
        </Typography>
        
        <Alert severity="info" sx={{ mb: 3 }}>
          <Box>
            <Typography variant="subtitle1" fontWeight="medium">Tips for creating effective email campaigns:</Typography>
            <ol>
              <li>Keep your message clear and concise</li>
              <li>Include a strong call-to-action</li>
              <li>Test your email on different devices before sending</li>
              <li>Personalize content where possible using user variables (including the curly braces), currently we support:  
                <ol>
                  <li>{`{{first_name}}`}</li>
                  <li>{`{{last_name}}`}</li>
                  <li>{`{{email}}`}</li>
                </ol>
              </li>
              <li>Add alt text to images for better accessibility</li>
            </ol>
          </Box>
        </Alert>

        <Box sx={{ border: '1px solid', borderColor: 'divider', borderRadius: 1, height: '600px', mb: 3 }}>
          <EmailEditor
            ref={emailEditorRef}
            onReady={onEditorReady}
            minHeight="600px"
          />
        </Box>
        
        <Box display="flex" justifyContent="space-between">
          <Button
            variant="outlined"
            startIcon={<PreviewIcon />}
            onClick={handlePreview}
          >
            Preview
          </Button>
          
          <Box>
            <Button
              variant="outlined"
              onClick={() => navigate('/admin/email-campaigns')}
              sx={{ mr: 2 }}
            >
              Cancel
            </Button>
            
            <Button
              variant="outlined"
              startIcon={<SaveIcon />}
              onClick={() => handleSave(true)}
              sx={{ mr: 2 }}
              disabled={createCampaign.isLoading || updateCampaign.isLoading}
            >
              {createCampaign.isLoading || updateCampaign.isLoading ? 
                <CircularProgress size={24} /> : 'Save & Exit'}
            </Button>
            
            {!isNewCampaign && <Button
              variant="contained"
              startIcon={<SendIcon />}
              onClick={handleSendCampaign}
              disabled={formData.listIds.length === 0 || !formData.subject}
              color="primary"
            >
              {'Next: Review & Send'}
            </Button>}
          </Box>
        </Box>
      </Paper>

      {/* Preview Dialog */}
      <Dialog 
        open={previewDialogOpen} 
        onClose={() => setPreviewDialogOpen(false)} 
        maxWidth="md" 
        fullWidth
      >
        <DialogTitle>
          Email Preview
          <Typography variant="caption" display="block" color="text.secondary">
            This is how your email will appear to recipients
          </Typography>
        </DialogTitle>
        <DialogContent>
          <Box dangerouslySetInnerHTML={{ __html: previewContent }} />
        </DialogContent>
        <DialogActions>
          <Button onClick={() => setPreviewDialogOpen(false)}>Close</Button>
        </DialogActions>
      </Dialog>

      {/* Segment Configuration Dialog */}
      <Dialog
        open={segmentDialogOpen}
        onClose={() => setSegmentDialogOpen(false)}
        maxWidth="md"
        fullWidth
      >
        <DialogTitle>Configure Audience Segments</DialogTitle>
        <DialogContent>
          <Typography paragraph>
            Segmentation allows you to target specific groups within your selected mailing lists.
            Define conditions below to narrow down your audience.
          </Typography>
          
          {/* Segmentation logic would go here */}
          <Alert severity="info">
            Advanced segmentation features will be implemented in a future update.
          </Alert>
        </DialogContent>
        <DialogActions>
          <Button onClick={() => setSegmentDialogOpen(false)}>Close</Button>
        </DialogActions>
      </Dialog>
    </Box>
  );
};

export default EmailCampaignEditor;