import React, {useState, useEffect} from 'react';
import {
    Box,
    CircularProgress,
    IconButton,
    Paper,
    Table,
    TableBody,
    TableCell,
    TableContainer,
    TableHead,
    TableRow,
    TableSortLabel,
    TextField,
    ThemeProvider,
    Typography,
    MenuItem,
    Button
} from '@mui/material';

import {
    Cancel as CancelIcon,
    Clear as ClearIcon,
    Email as EmailIcon,
    Search as SearchIcon
} from '@mui/icons-material';

import getIconComponent from '../Common/CustomSortIcon';
import CustomPagination from '../Common/CustomPagination';
import theme from '../Common/Theme';
import EmailPreviewDialog from './EmailPreviewDialog';
import CheckIcon from '@mui/icons-material/Check';
import InputAdornment from '@mui/material/InputAdornment';

export const OutStandingEmails = ({baseUrl, defaultRowPerPageOptions}: {
    baseUrl: string,
    defaultRowPerPageOptions: any,
}) => {
    const [emailData, setEmailData] = useState([]);
    const [loading, setLoading] = useState(false);
    const [error, setError] = useState<string | null>(null);
    const [role, setRole] = useState('');
    const [startDate, setStartDate] = useState('');
    const [endDate, setEndDate] = useState('');
    const [sortBy, setSortBy] = useState('senddate');
    const [sortDirection, setSortDirection] = useState<'asc' | 'desc'>('desc');
    const [page, setPage] = useState(1);
    const [rowsPerPage, setRowsPerPage] = useState(30);
    const [totalRecords, setTotalRecords] = useState(0);
    const [searchInput, setSearchInput] = useState('');
    const [search, setSearch] = useState('');
    const [previewOpen, setPreviewOpen] = useState(false);
    const [previewData, setPreviewData] = useState<EmailData | null>(null);
    const [loadingPreview, setLoadingPreview] = useState(false);
    const [dateError, setDateError] = useState('');

    const handleDownloadCSV = async () => {
        try {
            const params = new URLSearchParams({
                order_by: sortBy || 'id',
                order_direction: sortDirection.toUpperCase(),
                page: page.toString(),
                perPage: rowsPerPage.toString()
            });

            if (search.trim()) {
                params.append('search', search.trim());
            }
            if (startDate) params.append('start_date', startDate);
            if (endDate) params.append('end_date', endDate);
            if (role) params.append('role', role);


            const response = await fetch(`${baseUrl}emails?${params.toString()}`, {
                headers: {'X-Requested-With': 'XMLHttpRequest'}
            });

            const result = await response.json();
            const rows = result?.data ?? [];

            const headers = [
                'Creation Date',
                'Delivery Date',
                'Sent',
                'Sent By',
                'Delivered To',
                'Subject',
                'Sender Role'
            ];

            const csvRows = [
                headers.join(','),
                ...rows.map(row => [
                    row.creationdate,
                     row.senddate,
                     row.emailsent?.trim() ? row.emailsent : 'Email Not Sent', // emailsent fallback
                     row.sender_email?.trim() || row.sender_user_id || 'Not available', // sender fallback
                      row.emailtarget,
                    `"${row.subject}"`,
                    row.sender_role_name ?? '',
                ].join(','))
            ];

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

            const link = document.createElement('a');
            link.href = url;
            link.setAttribute('download', 'outstanding_emails.csv');
            document.body.appendChild(link);
            link.click();
            document.body.removeChild(link);
        } catch (error) {
            console.error('CSV download failed:', error);
        }
    };

    const roleOptions = [
        {value: '', label: 'All'},
        {value: 'PLK_ADMIN', label: 'Admin'},
        {value: 'PLK_STAFF', label: 'Staff'},
        {value: 'PLK_STUDENT', label: 'Student'},
        {value: 'PLK_PARENT', label: 'Parent'},
        {value: 'PLK_APPLICANT', label: 'Applicant'},
        {value: 'PLK_SYSTEM', label: 'System Support'},
    ];

    useEffect(() => {
        if (startDate && endDate && new Date(endDate) < new Date(startDate)) {
            setDateError('End date cannot be earlier than start date.');
            return;
        }

        setDateError('');
        setLoading(true);
        setError(null);

        const params = new URLSearchParams({
            order_by: sortBy || 'id',
            order_direction: sortDirection.toUpperCase(),
            page: page.toString(),
            perPage: rowsPerPage.toString(),
        });

        if (search.trim()) params.append('search', search.trim());
        if (startDate) params.append('start_date', startDate);
        if (endDate) params.append('end_date', endDate);
        if (role) params.append('role', role);

        fetch(`${baseUrl}emails?${params.toString()}`, {
            headers: { 'X-Requested-With': 'XMLHttpRequest' }
        })
            .then((res) => {
                if (!res.ok) {
                    // Handle API-level errors
                    if (res.status === 404) {
                        throw new Error('No emails found (404).');
                    } else if (res.status === 302) {
                        throw new Error('Unexpected redirect occurred (302).');
                    } else {
                        throw new Error(`Request failed with status ${res.status}`);
                    }
                }
                return res.json();
            })
            .then((data) => {
                const emails = data.data || [];
                setEmailData(emails);
                setTotalRecords(data.pagination?.totalCount || emails.length);
            })
            .catch((err) => {
                setEmailData([]); // clear previous data
                setTotalRecords(0);
                setError('Unable to load emails at the moment. Please try again later.');
            })
            .finally(() => {
                setLoading(false);
            });

    }, [search, startDate, endDate, role, page, rowsPerPage, sortBy, sortDirection]);


   const handlePreviewClick = async (id: number) => {
        try {
            setLoadingPreview(true);
            setError(null);

            const res = await fetch(`${baseUrl}emails/${id}`, {
                headers: { 'X-Requested-With': 'XMLHttpRequest' },
            });

            if (!res.ok) {
                setError('Failed to load email preview');
                return;
            }

            const json = await res.json();

            const formattedAttachments = (json.files || []).map((file: any) => ({
                name: file.name,
                size: file.size,
                url: file.link || '#',
            }));

            setPreviewData({
                subject: json.subject,
                htmlBody: json.body || '<p>No content available.</p>',
                creationDate: json.creationdate,
                deliveryDate: json.senddate,
                to: json.emailtarget,
                replyAddress: json.emailreplyaddress || 'None Available',
                attachments: formattedAttachments,
                institution: json.institution,
                topBanner: json.topBanner,
                bottomBanner: json.bottomBanner,
                url:json.url,
            });

            setPreviewOpen(true);
        } catch (error) {
            console.error('Failed to fetch email preview:', error);
            setError('Failed to load email preview');
        } finally {
            setLoadingPreview(false);
        }
    };

    const handleSort = (column: string) => {
        const isAsc = sortBy === column && sortDirection === 'asc';
        setSortBy(column);
        setSortDirection(isAsc ? 'desc' : 'asc');
        setPage(1);
    };

    const formatDate = (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 '';
        }
    };
    const formatDateInput = (date: Date): string => {
        return date.toISOString().split('T')[0]; // yyyy-mm-dd
    };

    const handleCancelEmail = async (id: number) => {
        try {
            const response = await fetch(`${baseUrl}emails/${id}`, {
                method: 'DELETE',
                headers: {
                    'X-Requested-With': 'XMLHttpRequest',
                },
            });

            const data = await response.json();

            if (!response.ok || data.status !== 'success') {
                const errorMessage = data.message || 'Failed to cancel email';
                setError(errorMessage);
                return;
            }

            // Only update the UI if deletion was successful
            setEmailData(prev => prev.filter(email => email.id !== id));
            setTotalRecords(prev => prev - 1);
        } catch (err) {
            console.error('Cancellation error:', err);
            setError('Something went wrong while canceling the email.');
        }
    };


    return (
        <ThemeProvider theme={theme}>
            <Box sx={{p: 3}}>
                {error && (
                    <Box display="flex" justifyContent="center" mb={2}>
                        <Typography
                            component="div"
                            sx={{
                                background: "url(/Static/Icons/ui/ux2/appbar-alert.png) 0px -3px no-repeat",
                                backgroundSize: "contain",
                                backgroundColor: "var(--red)",
                                color: "#ffffff",
                                padding: "0.7em 1.5em 1.0em 3em",
                                borderRadius: "0.25em",
                                fontSize: "1em"
                            }}
                        >
                            {error}
                        </Typography>
                    </Box>
                )}

                <Paper sx={{p: 2}}>
                        {/* Filters */}
                        <Box
                            display="flex"
                            justifyContent="flex-end"
                            flexWrap="wrap"
                            gap={2}
                            mb={2}
                            alignItems="flex-start" // ⬅ keeps top alignment even if some fields are taller
                        >

                        {/* Filters Group */}
                        <Box display="flex" gap={2} flexWrap="wrap" alignItems="flex-start">
                            {/* Search Box */}
                            <Box sx={{ display: 'flex', flexDirection: 'column' }}>
                                <TextField
                                    size="small"
                                    placeholder="Search..."
                                    value={searchInput}
                                    onChange={(e) => setSearchInput(e.target.value)}
                                    onKeyDown={(e) => {
                                        if (e.key === 'Enter') {
                                            setPage(1);
                                            setSearch(searchInput.trim());
                                        }
                                    }}
                                    InputProps={{
                                        endAdornment: (
                                            <InputAdornment position="end">
                                                {searchInput && (
                                                    <IconButton
                                                        size="small"
                                                        onClick={() => {
                                                            setSearchInput('');
                                                            setSearch('');
                                                            setPage(1);
                                                        }}
                                                        aria-label="Clear search"
                                                    >
                                                        <ClearIcon fontSize="small" />
                                                    </IconButton>
                                                )}
                                                <IconButton
                                                    size="small"
                                                    onClick={() => {
                                                        setPage(1);
                                                        setSearch(searchInput.trim());
                                                    }}
                                                    aria-label="Search"
                                                >
                                                    <SearchIcon sx={{ color: 'text.secondary' }} />
                                                </IconButton>
                                            </InputAdornment>
                                        ),
                                    }}
                                />

                            </Box>
                            <TextField
                                label="Start Date"
                                type="date"
                                size="small"
                                value={startDate}
                                onChange={(e) => {
                                    setPage(1);
                                    setStartDate(e.target.value);
                                    setDateError(''); // Clear any previous date error
                                }}
                                InputLabelProps={{shrink: true}}
                                inputProps={{placeholder: 'dd-mm-yyyy'}}
                            />

                            {/* End Date */}
                            <TextField
                                label="End Date"
                                type="date"
                                size="small"
                                value={endDate}
                                onChange={(e) => {
                                    setPage(1);
                                    setEndDate(e.target.value);
                                    setDateError(''); // clear any previous date error
                                }}
                            InputLabelProps={{ shrink: true }}
                            error={Boolean(dateError)}          // red outline if error present
                            helperText={dateError || ' '}       // reserve space to avoid layout shift
                            FormHelperTextProps={{
                                sx: { ml: 0 },                    // keep helper text aligned with the field
                            }}
                            />

                            {/* Role Dropdown */}
                            <TextField
                                select
                                label="Sender Role"
                                size="small"
                                value={role}
                                onChange={(e) => {
                                    setPage(1);
                                    setRole(e.target.value);
                                }}
                                sx={{minWidth: 150}}
                            >
                                {roleOptions.map((option) => (
                                    <MenuItem key={option.value} value={option.value}>
                                        {option.label}
                                    </MenuItem>
                                ))}
                            </TextField>


                            {/* Reset Button */}
                            <Button
                                variant="outlined"
                                size="small"
                                sx={{
                                    height: 40,                // match MUI small TextField height
                                    alignSelf: 'flex-start',   // keep aligned with top when errors show
                                    boxSizing: 'border-box',   // prevent border from adding extra height
                                }}
                                onClick={() => {
                                    setSearch('');
                                    setSearchInput('');
                                    setStartDate('');
                                    setEndDate('');
                                    setRole('');
                                    setSortBy('senddate');             // default sort key
                                    setSortDirection('desc');    // default sort order
                                    setPage(1);
                                    setDateError('');
                                }}
                            >
                                Reset
                            </Button>

                        </Box>
                    </Box>
                    {/* Table */}
                    <TableContainer>
                        <Table stickyHeader>
                            <TableHead>
                                <TableRow>
                                    {[
                                        {key: 'creationdate', label: 'Creation Date'},
                                        {key: 'senddate', label: 'Delivery Date'},
                                        {key: 'emailsent', label: 'Sent'},
                                        {key: 'sender_display', label: 'Sent By'},
                                        {key: 'emailtarget', label: 'Delivered To'},
                                        {key: 'subject', label: 'Subject'},
                                        {key: 'senderrole', label: 'Sender Role'},
                                        {key: 'preview', label: 'Preview'},
                                        {key: 'cancel', label: 'Cancel'}
                                    ].map(({key, label}) => (
                                        <TableCell
                                            key={key}
                                            sx={
                                                ['creationdate', 'senddate'].includes(key)
                                                    ? {width: 160, minWidth: 160, maxWidth: 160}
                                                    : {}
                                            }
                                        >
                                            {['emailsent', 'preview', 'cancel'].includes(key) ? (
                                                <span>{label}</span>
                                            ) : (
                                                <TableSortLabel
                                                    active={sortBy === key}
                                                    direction={sortBy === key ? sortDirection : 'asc'}
                                                    onClick={() => handleSort(key)}
                                                    IconComponent={getIconComponent(sortBy === key, sortDirection)}
                                                >
                                                    {label}
                                                </TableSortLabel>
                                            )}
                                        </TableCell>
                                    ))}
                                </TableRow>
                            </TableHead>

                            <TableBody>
                                {loading ? (
                                    <TableRow>
                                        <TableCell colSpan={7} align="center">
                                            <CircularProgress/>
                                        </TableCell>
                                    </TableRow>
                                ) : emailData.length === 0 ? (
                                    <TableRow>
                                        <TableCell colSpan={9} align="center">No emails found.</TableCell>
                                    </TableRow>
                                ) : (
                                    emailData.map((row: any) => (
                                        <TableRow key={row.id}>
                                                <TableCell
                                                    align="center"
                                                    sx={{
                                                    width: 160,
                                                    minWidth: 160,
                                                    maxWidth: 160,
                                                    verticalAlign: 'middle',
                                                    }}
                                                >
                                                    {formatDate(row.creationdate)}
                                                </TableCell>
                                                <TableCell
                                                    align="center"
                                                    sx={{
                                                    width: 160,
                                                    minWidth: 160,
                                                    maxWidth: 160,
                                                    verticalAlign: 'middle',
                                                    }}
                                                >
                                                    {formatDate(row.senddate)}
                                                </TableCell>

                                            {/* Sent Icon Centered */}
                                            <TableCell>
                                                <Box display="flex" justifyContent="center">
                                                    {row.emailsent ? (
                                                        <CheckIcon sx={{color: 'green', fontSize: 18}}/>
                                                    ) : (
                                                        <ClearIcon sx={{color: 'red', fontSize: 18}}/>
                                                    )}
                                                </Box>
                                            </TableCell>

                                            <TableCell>
                                                {row.sender_display}
                                            </TableCell>
                                            <TableCell>
                                                {row.emailtarget ? (
                                                    <a
                                                        href={`${window.location.origin}/admin/outstandingemails/viewemailhistory?email=${encodeURIComponent(row.emailtarget)}`}
                                                        rel="noopener noreferrer"
                                                    >
                                                        {row.emailtarget}
                                                    </a>
                                                ) : (
                                                    row.emailtarget || 'Not Available'
                                                )}
                                            </TableCell>

                                            <TableCell>{row.subject}</TableCell>
                                            <TableCell>{row.sender_role_name || 'Not Available'}</TableCell>

                                            {/* Preview Icon Centered */}
                                            <TableCell>
                                                <Box display="flex" justifyContent="center">
                                                    <IconButton
                                                        onClick={() => handlePreviewClick(row.id)}
                                                        disabled={loadingPreview}
                                                        aria-label="Preview Email" // Accessible name for screen readers
                                                        title="Preview Email"      // Tooltip for visual users
                                                    >
                                                        <EmailIcon fontSize="small"/>
                                                    </IconButton>
                                                </Box>
                                            </TableCell>


                                            {/* Cancel Icon Centered */}
                                            <TableCell>
                                                <Box display="flex" justifyContent="center">
                                                    <IconButton
                                                        onClick={() => handleCancelEmail(row.id)}
                                                        aria-label="Cancel Email"
                                                    >
                                                        <CancelIcon sx={{color: 'red', fontSize: 20}}/>
                                                    </IconButton>
                                                </Box>
                                            </TableCell>
                                        </TableRow>

                                    ))
                                )}
                            </TableBody>
                        </Table>
                    </TableContainer>
                    {/* Pagination */}
                    {totalRecords > 0 && (
                        <CustomPagination
                            totalRecords={totalRecords}
                            page={page}
                            rowsPerPage={rowsPerPage}
                            onPageChange={(newPage) => setPage(newPage)}
                            onRowsPerPageChange={(newRows) => {
                                setPage(1);
                                setRowsPerPage(newRows);
                            }}
                            rowsPerPageOptions={defaultRowPerPageOptions}
                        />
                    )}
                    <Box sx={{display: 'flex', flexDirection: 'column', gap: 2, mt: 2}}>
                        {/* Row 2: Download Button */}
                        <Box sx={{display: 'flex', justifyContent: 'flex-end', mt: 1}}>
                            <Button
                                variant="outlined"
                                size="small"
                                onClick={handleDownloadCSV}
                                disabled={Boolean(error) || emailData.length === 0}
                                startIcon={
                                    <Box
                                        component="img"
                                        src="/Static/Icons/ui/ux2/appbar-table-067a40.png"
                                        alt="Download"
                                        sx={{
                                            width: 20,
                                            height: 20,
                                            transition: 'filter 0.3s',
                                        }}
                                        className="download-icon"
                                    />
                                }
                                sx={{
                                    borderColor: '#067a40',
                                    color: '#067a40',
                                    backgroundColor: 'white',
                                    textTransform: 'none',
                                    '&:hover': {
                                        backgroundColor: '#067a40',
                                        color: 'white',
                                        '& .download-icon': {
                                            content: 'url("/Static/Icons/ui/ux2/appbar-table.png")',
                                        },
                                    },
                                    '&.Mui-disabled': {
                                        opacity: 0.5,
                                        pointerEvents: 'none',
                                    },
                                }}
                            >
                                Download spreadsheet
                            </Button>
                        </Box>
                    </Box>

                </Paper>
                <EmailPreviewDialog
                    open={previewOpen}
                    onClose={() => setPreviewOpen(false)}
                    emailData={previewData}
                />

            </Box>
        </ThemeProvider>
    );
};
