import React, {useState} from 'react';
import Draggable from 'react-draggable';

import {
    Dialog,
    DialogTitle,
    DialogContent,
    Paper,
    IconButton,
    Typography,
    Table,
    TableBody,
    TableRow,
    TableCell,
    Link,
    Box,
    Button,
    TableHead,
    TableSortLabel
} from '@mui/material';

import CloseIcon from '@mui/icons-material/Close';
import getIconComponent from '../Common/CustomSortIcon';

const formatDisplayDate = (dateStr: string): string => {
    if (!dateStr) return '';
    try {
        const date = new Date(dateStr);
        const day = String(date.getDate()).padStart(2, '0');
        const month = date.toLocaleString('en-GB', {month: 'short'});
        const year = String(date.getFullYear()).slice(-2);
        const hours = String(date.getHours()).padStart(2, '0');
        const minutes = String(date.getMinutes()).padStart(2, '0');
        return `${day}-${month}-${year} ${hours}:${minutes}`;
    } catch {
        return '';
    }
};

interface Attachment {
    name: string;
    size: string;
    url: string;
}

interface EmailData {
    subject: string;
    htmlBody: string;
    creationDate: string;
    deliveryDate: string;
    to: string;
    replyAddress?: string | null;
    attachments?: Attachment[];
    topBanner?: string | null;
    bottomBanner?: string | null;
    institution?: string; // Optional override
    url?: string
}

interface EmailPreviewDialogProps {
    open: boolean;
    onClose: () => void;
    emailData: EmailData | null;
}

function PaperComponent(props: any) {
    return (
        <Draggable handle="#draggable-dialog-title" cancel={'[class*="MuiDialogContent-root"]'}>
            <Paper {...props} />
        </Draggable>
    );
}

const EmailPreviewDialog: React.FC<EmailPreviewDialogProps> = ({
                                                                   open,
                                                                   onClose,
                                                                   emailData,
                                                               }) => {
    if (!emailData) return null;

    const [sortConfig, setSortConfig] = useState({key: 'name', direction: 'asc'});
    const [isHovered, setIsHovered] = useState(false);

    const {
        subject,
        htmlBody,
        creationDate,
        deliveryDate,
        to,
        replyAddress,
        attachments = [],
        topBanner,
        bottomBanner,
        institution,
        url
    } = emailData;

    const handleDownload = () => {
        if (!attachments || attachments.length === 0) return;

        const csvContent = ['Name,Size']
            .concat(attachments.map(att => `${att.name},${att.size}`))
            .join('\n');

        const blob = new Blob([csvContent], {type: 'text/csv;charset=utf-8;'});
        const url = URL.createObjectURL(blob);

        const a = document.createElement('a');
        a.href = url;
        a.download = 'attachments.csv';
        a.click();
        URL.revokeObjectURL(url);
    };

    const handleAttachmentSort = (key: 'name' | 'size') => {
        setSortConfig(prev => ({
            key,
            direction: prev.key === key && prev.direction === 'asc' ? 'desc' : 'asc',
        }));
    };

    const sortedAttachments = [...attachments].sort((a, b) => {
        const {key, direction} = sortConfig;

        const aVal = key === 'size' ? parseFloat(a.size) || 0 : a.name.toLowerCase();
        const bVal = key === 'size' ? parseFloat(b.size) || 0 : b.name.toLowerCase();

        if (aVal < bVal) return direction === 'asc' ? -1 : 1;
        if (aVal > bVal) return direction === 'asc' ? 1 : -1;
        return 0;
    });


    return (
        <Dialog
            open={open}
            onClose={onClose}
            PaperComponent={PaperComponent}
            maxWidth="lg"
            fullWidth
        >
            <DialogTitle
                id="draggable-dialog-title"
                sx={{
                    cursor: 'move',
                    backgroundColor: '#067a40',
                    color: '#fff',
                    px: 3,
                    py: 2,
                    borderBottom: '4px solid #067a40'
                }}
            >
                <Box display="flex" justifyContent="flex-end" alignItems="center">
                    <IconButton onClick={onClose} sx={{color: '#fff'}}>
                        <CloseIcon/>
                    </IconButton>
                </Box>
            </DialogTitle>

            <DialogContent
                dividers
                sx={{padding: 3, borderTop: 'none', borderBottom: 'none'}} // Hides the grey top border
            >
                <Box sx={{mb: 4}}>
                    <Box
                        sx={{
                            border: '1px solid #067a40',
                            backgroundColor: '#067a40',
                            color: '#ffffff',
                            fontSize: 24,
                            padding: 2,
                            fontWeight: 'bold',
                            fontFamily: 'Calibri, Arial, sans-serif',
                            textAlign: 'left',
                        }}
                    >

                        <Typography variant="h6" sx={{fontSize: 24, fontWeight: 'bold'}}>
                            {institution} - CEDAR Messaging Service
                        </Typography>

                        {topBanner && (
                            <Box
                                sx={{
                                    mt: 1,
                                    fontSize: 16,
                                    '& p': {marginBottom: 0} // Remove bottom margin from <p>
                                }}
                                dangerouslySetInnerHTML={{__html: topBanner}}
                            />
                        )}
                    </Box>

                    <Box
                        sx={{
                            border: '1px solid #4AC441',
                            backgroundColor: '#ffffff',
                            padding: '16px 16px 8px', // top: 16px, sides: 16px, bottom: 8px
                            fontFamily: 'Calibri, Arial, sans-serif',
                            fontSize: 16,
                            color: '#2E3D2C',
                            textAlign: 'left'
                        }}
                    >
                        <Typography variant="h5" sx={{mb: 2}}>{subject}</Typography>

                        <div dangerouslySetInnerHTML={{ __html: htmlBody }} />

                        {/* Show URL after HTML body */}
                        {url && (
                            <Box sx={{ mt: 0.2, mb: 1.5 }}>
                                <Typography
                                    variant="body1"
                                    sx={{
                                        fontFamily: 'Calibri, Arial, sans-serif',
                                        color: '#067a40',
                                        wordBreak: 'break-all',
                                    }}
                                >
                                    
                                    <Link
                                        href={url}
                                        target="_blank"
                                        rel="noopener noreferrer"
                                        underline="hover"
                                        sx={{ color: '#067a40', fontWeight: 500 }}
                                    >
                                        {url}
                                    </Link>
                                </Typography>
                            </Box>
                        )}

                        {bottomBanner && (
                            <Box
                                sx={{ mt: 1 }}
                                dangerouslySetInnerHTML={{ __html: bottomBanner }}
                            />
                        )}

                    </Box>
                </Box>

                {/* Email Details Section */}
                <Box sx={{mb: 4}}>
                    <Typography variant="h6" gutterBottom>Email Details</Typography>
                    <Table>
                        <TableBody>
                            <TableRow>
                                <TableCell>
                                    <strong>Creation Date / Time</strong>
                                    <div>{formatDisplayDate(creationDate)}</div>
                                    <strong>Delivery Date / Time</strong>
                                    <div>{formatDisplayDate(deliveryDate)}</div>
                                </TableCell>
                                <TableCell>
                                    <strong>Target Email</strong>
                                    <div>{to || 'None Available'}</div>
                                    <strong>Reply Address</strong>
                                    <div>{replyAddress || 'None Available'}</div>
                                </TableCell>
                            </TableRow>
                        </TableBody>
                    </Table>
                </Box>

                {/* Attachments */}
                {attachments.length > 0 ? (
                    <Box>
                        <Typography variant="h6" gutterBottom>Attachments</Typography>
                        <Table>
                            <TableHead>
                                <TableRow>
                                    <TableCell sortDirection={sortConfig.key === 'name' ? sortConfig.direction : false}>
                                        <TableSortLabel
                                            active={sortConfig.key === 'name'}
                                            direction={sortConfig.key === 'name' ? sortConfig.direction : 'asc'}
                                            onClick={() => handleAttachmentSort('name')}
                                            IconComponent={getIconComponent(sortConfig.key === 'name', sortConfig.direction)}
                                        >
                                            Name
                                        </TableSortLabel>
                                    </TableCell>

                                    <TableCell sortDirection={sortConfig.key === 'size' ? sortConfig.direction : false}>
                                        <TableSortLabel
                                            active={sortConfig.key === 'size'}
                                            direction={sortConfig.key === 'size' ? sortConfig.direction : 'asc'}
                                            onClick={() => handleAttachmentSort('size')}
                                            IconComponent={getIconComponent(sortConfig.key === 'size', sortConfig.direction)}
                                        >
                                            Size
                                        </TableSortLabel>
                                    </TableCell>

                                </TableRow>
                            </TableHead>
                            <TableBody>
                                {sortedAttachments.map((att, index) => (
                                    <TableRow key={index}>
                                        <TableCell>
                                            <Link href={att.url} target="_blank" rel="noopener noreferrer">
                                                {att.name}
                                            </Link>
                                        </TableCell>
                                        <TableCell>{att.size}</TableCell>
                                    </TableRow>
                                ))}
                            </TableBody>
                        </Table>
                    </Box>
                ) : (
                    <Box>
                        <Typography variant="h6" gutterBottom>Attachments</Typography>
                        <Box
                            sx={{
                                borderRadius: 2,
                                backgroundColor: '#f9f9f9',
                                padding: 2,
                                mt: 1,
                                textAlign: 'center',
                            }}
                        >
                            <Typography
                                component="p"
                                className="message unimportant"
                                sx={{
                                    fontSize: '1.1rem',
                                    color: '#444',
                                    fontFamily: 'Calibri, Arial, sans-serif',
                                    m: 0,
                                }}
                            >
                                No files attached to this email
                            </Typography>
                        </Box>
                    </Box>
                )}

            </DialogContent>

            {attachments?.length > 0 && (
                <Box
                    sx={{
                        display: 'flex',
                        justifyContent: 'flex-end',
                        alignItems: 'center',
                        p: 2,
                        pt: 0,
                        borderTop: 'none' // removes top grey border
                    }}
                >
                    <Button
                        variant="outlined"
                        onClick={handleDownload}
                        onMouseEnter={() => setIsHovered(true)}
                        onMouseLeave={() => setIsHovered(false)}
                        startIcon={
                            <Box
                                component="img"
                                src={
                                    isHovered
                                        ? '/Static/Icons/ui/ux2/appbar-table.png'
                                        : '/Static/Icons/ui/ux2/appbar-table-067a40.png'
                                }
                                alt="Download"
                                sx={{width: 20, height: 20}}
                            />
                        }
                        sx={{
                            textTransform: 'none',
                            color: '#067a40',
                            borderColor: '#067a40',
                            '&:hover': {
                                backgroundColor: '#067a40',
                                color: '#ffffff',
                                borderColor: '#067a40'
                            }
                        }}
                    >
                        Download spreadsheet
                    </Button>
                </Box>
            )}
        </Dialog>
    );
};

export default EmailPreviewDialog;
