/**
 * @ai-summary Admin Email Templates page for managing notification email templates
 * @ai-context Desktop version with template list and edit dialog
 */

import React, { useState, useCallback } from 'react';
import { Navigate } from 'react-router-dom';
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
import {
  Box,
  Button,
  Card,
  CardContent,
  CardActions,
  Chip,
  CircularProgress,
  Container,
  Dialog,
  DialogActions,
  DialogContent,
  DialogTitle,
  FormControlLabel,
  Grid,
  Switch,
  TextField,
  Typography,
  Alert,
  Divider,
} from '@mui/material';
import { Email, Edit, Visibility, Send } from '@mui/icons-material';
import toast from 'react-hot-toast';
import { useAdminAccess } from '../../core/auth/useAdminAccess';
import { adminApi } from '../../features/admin/api/admin.api';
import { Box as MuiBox } from '@mui/material';
import { EmailTemplate, UpdateEmailTemplateRequest } from '../../features/admin/types/admin.types';

const SAMPLE_VARIABLES: Record<string, string> = {
  userName: 'John Doe',
  vehicleName: '2024 Toyota Camry',
  category: 'Routine Maintenance',
  subtypes: 'Oil Change, Air Filter',
  dueDate: '2025-01-15',
  dueMileage: '50,000',
  documentType: 'Insurance',
  documentTitle: 'State Farm Policy',
  expirationDate: '2025-02-28',
};

export const AdminEmailTemplatesPage: React.FC = () => {
  const { loading: authLoading, isAdmin } = useAdminAccess();
  const queryClient = useQueryClient();

  // State
  const [editDialogOpen, setEditDialogOpen] = useState(false);
  const [previewDialogOpen, setPreviewDialogOpen] = useState(false);
  const [selectedTemplate, setSelectedTemplate] = useState<EmailTemplate | null>(null);
  const [editSubject, setEditSubject] = useState('');
  const [editBody, setEditBody] = useState('');
  const [editIsActive, setEditIsActive] = useState(true);
  const [previewSubject, setPreviewSubject] = useState('');
  const [previewBody, setPreviewBody] = useState('');
  const [previewHtml, setPreviewHtml] = useState('');
  const [showHtmlPreview, setShowHtmlPreview] = useState(false);

  // Queries
  const { data: templates, isLoading } = useQuery({
    queryKey: ['admin', 'emailTemplates'],
    queryFn: () => adminApi.emailTemplates.list(),
    enabled: isAdmin,
  });

  // Mutations
  const updateMutation = useMutation({
    mutationFn: ({ key, data }: { key: string; data: UpdateEmailTemplateRequest }) =>
      adminApi.emailTemplates.update(key, data),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['admin', 'emailTemplates'] });
      toast.success('Email template updated successfully');
      handleCloseEditDialog();
    },
    onError: () => {
      toast.error('Failed to update email template');
    },
  });

  const previewMutation = useMutation({
    mutationFn: ({ key, variables }: { key: string; variables: Record<string, string> }) =>
      adminApi.emailTemplates.preview(key, variables),
    onSuccess: (data) => {
      setPreviewSubject(data.subject);
      setPreviewBody(data.body);
      setPreviewHtml(data.html || '');
      setPreviewDialogOpen(true);
    },
    onError: () => {
      toast.error('Failed to generate preview');
    },
  });

  const sendTestMutation = useMutation({
    mutationFn: (key: string) => adminApi.emailTemplates.sendTest(key),
    onSuccess: (data) => {
      if (data.error) {
        toast.error(`Test email failed: ${data.error}`);
      } else if (data.message) {
        toast.success(data.message);
      }
    },
    onError: () => {
      toast.error('Failed to send test email');
    },
  });

  // Handlers
  const handleEditClick = useCallback((template: EmailTemplate) => {
    setSelectedTemplate(template);
    setEditSubject(template.subject);
    setEditBody(template.body);
    setEditIsActive(template.isActive);
    setEditDialogOpen(true);
  }, []);

  const handlePreviewClick = useCallback((template: EmailTemplate) => {
    setSelectedTemplate(template);
    previewMutation.mutate({
      key: template.templateKey,
      variables: SAMPLE_VARIABLES,
    });
  }, [previewMutation]);

  const handleSendTestClick = useCallback((template: EmailTemplate) => {
    sendTestMutation.mutate(template.templateKey);
  }, [sendTestMutation]);

  const handleCloseEditDialog = useCallback(() => {
    setEditDialogOpen(false);
    setSelectedTemplate(null);
    setEditSubject('');
    setEditBody('');
    setEditIsActive(true);
  }, []);

  const handleClosePreviewDialog = useCallback(() => {
    setPreviewDialogOpen(false);
    setPreviewSubject('');
    setPreviewBody('');
    setPreviewHtml('');
    setShowHtmlPreview(false);
  }, []);

  const handleSave = useCallback(() => {
    if (!selectedTemplate) return;

    const data: UpdateEmailTemplateRequest = {
      subject: editSubject !== selectedTemplate.subject ? editSubject : undefined,
      body: editBody !== selectedTemplate.body ? editBody : undefined,
      isActive: editIsActive !== selectedTemplate.isActive ? editIsActive : undefined,
    };

    // Only update if there are changes
    if (data.subject || data.body || data.isActive !== undefined) {
      updateMutation.mutate({
        key: selectedTemplate.templateKey,
        data,
      });
    } else {
      handleCloseEditDialog();
    }
  }, [selectedTemplate, editSubject, editBody, editIsActive, updateMutation, handleCloseEditDialog]);

  // Auth loading
  if (authLoading) {
    return (
      <Container maxWidth="lg" sx={{ py: 4 }}>
        <Box display="flex" justifyContent="center" alignItems="center" minHeight="400px">
          <CircularProgress />
        </Box>
      </Container>
    );
  }

  // Not admin
  if (!isAdmin) {
    return <Navigate to="/garage/settings" replace />;
  }

  return (
    <Container maxWidth="lg" sx={{ py: 4 }}>
      <MuiBox sx={{ mb: 4 }}>
        <Typography variant="h4" component="h1" sx={{ mb: 1, fontWeight: 600 }}>
          <Box display="flex" alignItems="center" gap={2}>
            <Email />
            Email Templates
          </Box>
        </Typography>
        <Typography variant="body1" color="text.secondary">
          Manage notification email templates
        </Typography>
      </MuiBox>

      <Box sx={{ mt: 4 }}>
        {isLoading ? (
          <Box display="flex" justifyContent="center" py={8}>
            <CircularProgress />
          </Box>
        ) : (
          <Grid container spacing={3}>
            {templates?.map((template) => (
              <Grid item xs={12} md={6} key={template.id}>
                <Card>
                  <CardContent>
                    <Box display="flex" justifyContent="space-between" alignItems="start" mb={2}>
                      <Typography variant="h6" component="div">
                        {template.name}
                      </Typography>
                      <Chip
                        label={template.isActive ? 'Active' : 'Inactive'}
                        color={template.isActive ? 'success' : 'default'}
                        size="small"
                      />
                    </Box>

                    {template.description && (
                      <Typography variant="body2" color="text.secondary" gutterBottom>
                        {template.description}
                      </Typography>
                    )}

                    <Divider sx={{ my: 2 }} />

                    <Typography variant="subtitle2" gutterBottom>
                      Subject
                    </Typography>
                    <Typography
                      variant="body2"
                      color="text.secondary"
                      gutterBottom
                      sx={{
                        overflow: 'hidden',
                        textOverflow: 'ellipsis',
                        whiteSpace: 'nowrap',
                      }}
                    >
                      {template.subject}
                    </Typography>

                    <Typography variant="subtitle2" gutterBottom sx={{ mt: 2 }}>
                      Available Variables
                    </Typography>
                    <Box display="flex" flexWrap="wrap" gap={0.5}>
                      {template.variables.map((variable) => (
                        <Chip
                          key={variable}
                          label={`{{${variable}}}`}
                          size="small"
                          variant="outlined"
                        />
                      ))}
                    </Box>
                  </CardContent>

                  <CardActions>
                    <Button
                      size="small"
                      startIcon={<Edit />}
                      onClick={() => handleEditClick(template)}
                    >
                      Edit
                    </Button>
                    <Button
                      size="small"
                      startIcon={<Visibility />}
                      onClick={() => handlePreviewClick(template)}
                    >
                      Preview
                    </Button>
                    <Button
                      size="small"
                      startIcon={<Send />}
                      onClick={() => handleSendTestClick(template)}
                      disabled={sendTestMutation.isPending}
                    >
                      {sendTestMutation.isPending ? 'Sending...' : 'Send Test'}
                    </Button>
                  </CardActions>
                </Card>
              </Grid>
            ))}
          </Grid>
        )}
      </Box>

      {/* Edit Dialog */}
      <Dialog
        open={editDialogOpen}
        onClose={handleCloseEditDialog}
        maxWidth="md"
        fullWidth
      >
        <DialogTitle>
          Edit Template: {selectedTemplate?.name}
        </DialogTitle>
        <DialogContent>
          <Box sx={{ mt: 2, display: 'flex', flexDirection: 'column', gap: 3 }}>
            <FormControlLabel
              control={
                <Switch
                  checked={editIsActive}
                  onChange={(e) => setEditIsActive(e.target.checked)}
                />
              }
              label="Active"
            />

            <TextField
              label="Subject"
              fullWidth
              value={editSubject}
              onChange={(e) => setEditSubject(e.target.value)}
              helperText="Use {{variableName}} for dynamic content"
            />

            <TextField
              label="Body"
              fullWidth
              multiline
              rows={12}
              value={editBody}
              onChange={(e) => setEditBody(e.target.value)}
              helperText="Use {{variableName}} for dynamic content"
              inputProps={{
                style: { fontFamily: 'monospace' },
              }}
            />

            <Alert severity="info">
              Available variables:{' '}
              {selectedTemplate?.variables.map((v) => `{{${v}}}`).join(', ')}
            </Alert>
          </Box>
        </DialogContent>
        <DialogActions>
          <Button onClick={handleCloseEditDialog}>Cancel</Button>
          <Button
            onClick={handleSave}
            variant="contained"
            disabled={updateMutation.isPending}
          >
            {updateMutation.isPending ? 'Saving...' : 'Save'}
          </Button>
        </DialogActions>
      </Dialog>

      {/* Preview Dialog */}
      <Dialog
        open={previewDialogOpen}
        onClose={handleClosePreviewDialog}
        maxWidth="md"
        fullWidth
      >
        <DialogTitle>
          Preview: {selectedTemplate?.name}
        </DialogTitle>
        <DialogContent>
          <Box sx={{ mt: 2, display: 'flex', flexDirection: 'column', gap: 3 }}>
            <Alert severity="info">
              This preview uses sample data to show how the template will appear.
            </Alert>

            <FormControlLabel
              control={
                <Switch
                  checked={showHtmlPreview}
                  onChange={(e) => setShowHtmlPreview(e.target.checked)}
                />
              }
              label="Show HTML Preview"
            />

            <TextField
              label="Subject"
              fullWidth
              value={previewSubject}
              InputProps={{
                readOnly: true,
              }}
            />

            {showHtmlPreview ? (
              <Box>
                <Typography variant="subtitle2" gutterBottom>
                  HTML Preview
                </Typography>
                <Box
                  sx={{
                    border: '1px solid #e2e8f0',
                    borderRadius: 1,
                    overflow: 'hidden',
                    backgroundColor: '#f8f9fa',
                  }}
                >
                  <iframe
                    srcDoc={previewHtml}
                    style={{ width: '100%', height: '500px', border: 'none' }}
                    title="Email HTML Preview"
                  />
                </Box>
              </Box>
            ) : (
              <TextField
                label="Body (Plain Text)"
                fullWidth
                multiline
                rows={12}
                value={previewBody}
                InputProps={{
                  readOnly: true,
                }}
                inputProps={{
                  style: { fontFamily: 'monospace' },
                }}
              />
            )}
          </Box>
        </DialogContent>
        <DialogActions>
          <Button onClick={handleClosePreviewDialog}>Close</Button>
        </DialogActions>
      </Dialog>
    </Container>
  );
};
