'use client';

import * as React from 'react';
import RouterLink from 'next/link';
import { useParams } from 'next/navigation';
import {
  Alert,
  Box,
  Button,
  Card,
  CardContent,
  Chip,
  Divider,
  Grid,
  Stack,
  Typography,
  useTheme,
} from '@mui/material';
import { AppLoader } from '@/components/core/app-loader';
import {
  ArrowBack as ArrowBackIcon,
  Edit as EditIcon,
  Email as EmailIcon,
  Person as PersonIcon,
  Send as SendIcon,
  Subject as SubjectIcon,
  Title as TitleIcon,
} from '@mui/icons-material';
import { enqueueSnackbar } from 'notistack';

import { CreateNewsletterModal } from '@/components/dashboard/newsletter/create-newsletter-modal';
import {
  fetchNewsletterById,
  getApiErrorMessage,
  type Newsletter,
} from '@/services/newsletter.service';
import { paths } from '@/paths';

function formatDateTime(dateString?: string): string {
  if (!dateString) return '—';
  try {
    return new Date(dateString).toLocaleString('en-US', {
      year: 'numeric',
      month: 'short',
      day: 'numeric',
      hour: 'numeric',
      minute: '2-digit',
    });
  } catch {
    return '—';
  }
}

interface DetailFieldProps {
  icon: React.ReactNode;
  label: string;
  value: React.ReactNode;
}

function DetailField({ icon, label, value }: DetailFieldProps): React.JSX.Element {
  return (
    <Stack direction="row" spacing={2} alignItems="flex-start">
      <Box sx={{ color: 'text.secondary', mt: 0.25 }}>{icon}</Box>
      <Box sx={{ flex: 1 }}>
        <Typography variant="caption" color="text.secondary" fontWeight={600} sx={{ textTransform: 'uppercase' }}>
          {label}
        </Typography>
        <Box sx={{ mt: 0.5 }}>{value}</Box>
      </Box>
    </Stack>
  );
}

export function NewsletterDetail(): React.JSX.Element {
  const theme = useTheme();
  const params = useParams();
  const newsletterId = params?.id as string;

  const [newsletter, setNewsletter] = React.useState<Newsletter | null>(null);
  const [loading, setLoading] = React.useState(true);
  const [error, setError] = React.useState<string | null>(null);
  const [isEditModalOpen, setIsEditModalOpen] = React.useState(false);

  const loadNewsletter = React.useCallback(async () => {
    if (!newsletterId) {
      return;
    }

    try {
      setLoading(true);
      setError(null);
      const response = await fetchNewsletterById(newsletterId);
      setNewsletter(response.data.newsletter);
    } catch (err) {
      console.error('Error fetching newsletter:', err);
      const message = getApiErrorMessage(err, 'Failed to load newsletter');
      setError(message);
      enqueueSnackbar(message, { variant: 'error' });
    } finally {
      setLoading(false);
    }
  }, [newsletterId]);

  React.useEffect(() => {
    loadNewsletter();
  }, [loadNewsletter]);

  if (loading) {
    return <AppLoader size="lg" viewport="content" label="Loading newsletter details..." />;
  }

  if (error || !newsletter) {
    return (
      <Box>
        <Alert severity="error" sx={{ mb: 2 }}>
          {error || 'Newsletter not found'}
        </Alert>
        <Button
          component={RouterLink}
          href={paths.dashboard.newsletterNewsletters}
          variant="outlined"
          startIcon={<ArrowBackIcon />}
        >
          Back to Newsletters
        </Button>
      </Box>
    );
  }

  const sent = newsletter.emailsSent ?? 0;
  const total = newsletter.recipientsCount ?? sent;
  const failed = newsletter.emailsFailed ?? 0;

  return (
    <Box>
      <Stack
        direction={{ xs: 'column', sm: 'row' }}
        justifyContent="space-between"
        alignItems={{ xs: 'flex-start', sm: 'center' }}
        spacing={2}
        sx={{
          mb: 4,
          p: 3,
          borderRadius: 4,
          background: '#FFDD31',
          color: '#0B0504',
        }}
      >
        <Box>
          <Button
            component={RouterLink}
            href={paths.dashboard.newsletterNewsletters}
            startIcon={<ArrowBackIcon />}
            sx={{ mb: 1, color: '#0B0504', '&:hover': { bgcolor: 'rgba(11, 5, 4, 0.08)' } }}
          >
            Back to Newsletters
          </Button>
          <Typography variant="h4" fontWeight={700} gutterBottom>
            {newsletter.title}
          </Typography>
          <Typography variant="body1" sx={{ opacity: 0.9 }}>
            Newsletter details and content preview
          </Typography>
        </Box>
        <Button
          variant="contained"
          startIcon={<EditIcon />}
          onClick={() => setIsEditModalOpen(true)}
          sx={{
            bgcolor: 'rgba(11, 5, 4, 0.8)',
            color: '#FFDD31',
            '&:hover': { bgcolor: 'rgba(11, 5, 4, 0.9)' },
          }}
        >
          Edit Newsletter
        </Button>
      </Stack>

      <Grid container spacing={3}>
        <Grid item xs={12} md={4}>
          <Card sx={{ borderRadius: 3, boxShadow: theme.shadows[2], height: '100%' }}>
            <CardContent>
              <Typography variant="h6" fontWeight={700} gutterBottom>
                Overview
              </Typography>
              <Stack spacing={3} divider={<Divider flexItem />}>
                <DetailField
                  icon={<TitleIcon fontSize="small" />}
                  label="Title"
                  value={<Typography variant="body1">{newsletter.title}</Typography>}
                />
                <DetailField
                  icon={<SubjectIcon fontSize="small" />}
                  label="Email Subject"
                  value={<Typography variant="body1">{newsletter.subject}</Typography>}
                />
                <DetailField
                  icon={<PersonIcon fontSize="small" />}
                  label="Sent By"
                  value={
                    newsletter.sentBy ? (
                      <Box>
                        <Typography variant="body1" fontWeight={600}>
                          {newsletter.sentBy.fullName}
                        </Typography>
                        <Typography variant="body2" color="text.secondary">
                          {newsletter.sentBy.emailAddress}
                        </Typography>
                        {newsletter.sentBy.accountType && (
                          <Chip label={newsletter.sentBy.accountType} size="small" sx={{ mt: 1 }} />
                        )}
                      </Box>
                    ) : (
                      <Typography variant="body1">—</Typography>
                    )
                  }
                />
                <DetailField
                  icon={<SendIcon fontSize="small" />}
                  label="Delivery"
                  value={
                    newsletter.emailsSent !== undefined || newsletter.recipientsCount !== undefined ? (
                      <Box>
                        <Typography variant="body1">
                          {sent}/{total} emails sent
                        </Typography>
                        {failed > 0 && (
                          <Chip label={`${failed} failed`} size="small" color="error" sx={{ mt: 1 }} />
                        )}
                      </Box>
                    ) : (
                      <Typography variant="body1">—</Typography>
                    )
                  }
                />
                <DetailField
                  icon={<EmailIcon fontSize="small" />}
                  label="Created"
                  value={<Typography variant="body1">{formatDateTime(newsletter.createdAt)}</Typography>}
                />
                <DetailField
                  icon={<EmailIcon fontSize="small" />}
                  label="Last Updated"
                  value={<Typography variant="body1">{formatDateTime(newsletter.updatedAt)}</Typography>}
                />
              </Stack>
            </CardContent>
          </Card>
        </Grid>

        <Grid item xs={12} md={8}>
          <Card sx={{ borderRadius: 3, boxShadow: theme.shadows[2] }}>
            <CardContent>
              <Typography variant="h6" fontWeight={700} gutterBottom>
                Content Preview
              </Typography>
              <Typography variant="body2" color="text.secondary" sx={{ mb: 2 }}>
                This is how the newsletter content appears to recipients.
              </Typography>
              <Box
                sx={{
                  p: 3,
                  borderRadius: 2,
                  border: `1px solid ${theme.palette.divider}`,
                  bgcolor: theme.palette.mode === 'dark' ? 'background.default' : '#ffffff',
                  minHeight: 280,
                  '& img': { maxWidth: '100%' },
                  '& a': { color: theme.palette.primary.main },
                  '& ul, & ol': { pl: 3 },
                }}
                dangerouslySetInnerHTML={{ __html: newsletter.content }}
              />
            </CardContent>
          </Card>
        </Grid>
      </Grid>

      <CreateNewsletterModal
        open={isEditModalOpen}
        onClose={() => setIsEditModalOpen(false)}
        onSuccess={loadNewsletter}
        newsletterId={newsletter._id}
      />
    </Box>
  );
}
