"use client";

import { useState, useEffect } from 'react';
import {
    EnvelopeIcon,
    CheckCircleIcon,
    ExclamationCircleIcon,
    EyeIcon,
    XMarkIcon,
    ClockIcon
} from '@heroicons/react/24/outline';
import api from '../../lib/api';
import { format } from 'date-fns';

interface NotificationLog {
    id: number;
    notification_type: string;
    sent_at: string;
    subject: string;
    recipient_email: string;
    status: string;
    error_message: string | null;
    cve_id: string | null;
    asset_hostname: string | null;
    username: string | null;
    message_body: string | null;
}

export default function NotificationsPage() {
    const [logs, setLogs] = useState<NotificationLog[]>([]);
    const [loading, setLoading] = useState(true);
    const [previewLog, setPreviewLog] = useState<NotificationLog | null>(null);

    useEffect(() => {
        const fetchLogs = async () => {
            try {
                const response = await api.get('/api/v1/notifications/log');
                setLogs(response.data);
            } catch (error) {
                console.error("Failed to fetch notification logs", error);
            } finally {
                setLoading(false);
            }
        };
        fetchLogs();
    }, []);

    const getStatusIcon = (status: string) => {
        switch (status.toLowerCase()) {
            case 'sent':
                return <CheckCircleIcon className="h-5 w-5 text-green-500" />;
            case 'failed':
                return <ExclamationCircleIcon className="h-5 w-5 text-red-500" />;
            default:
                return <ClockIcon className="h-5 w-5 text-gray-400" />;
        }
    };

    return (
        <div className="space-y-6">
            <div className="flex items-center justify-between">
                <div>
                    <h1 className="text-2xl font-bold text-gray-900">Notification History</h1>
                    <p className="text-sm text-gray-500 mt-1">Audit log of all outbound emails and alerts.</p>
                </div>
                <div className="bg-white p-2 rounded-lg shadow-sm border border-gray-100 flex items-center gap-2">
                    <EnvelopeIcon className="h-5 w-5 text-vulncheck-blue" />
                    <span className="text-sm font-bold text-gray-700">{logs.length} Notifications</span>
                </div>
            </div>

            {loading ? (
                <div className="flex justify-center items-center h-64">
                    <div className="animate-spin rounded-full h-8 w-8 border-b-2 border-vulncheck-blue"></div>
                </div>
            ) : (
                <div className="bg-white shadow-sm border border-gray-100 rounded-xl overflow-hidden">
                    <table className="min-w-full divide-y divide-gray-200">
                        <thead className="bg-gray-50">
                            <tr>
                                <th className="px-6 py-3 text-left text-xs font-bold text-gray-500 uppercase tracking-wider">Status</th>
                                <th className="px-6 py-3 text-left text-xs font-bold text-gray-500 uppercase tracking-wider">Recipient</th>
                                <th className="px-6 py-3 text-left text-xs font-bold text-gray-500 uppercase tracking-wider">Subject</th>
                                <th className="px-6 py-3 text-left text-xs font-bold text-gray-500 uppercase tracking-wider">Sent At</th>
                                <th className="px-6 py-3 text-right text-xs font-bold text-gray-500 uppercase tracking-wider">Actions</th>
                            </tr>
                        </thead>
                        <tbody className="bg-white divide-y divide-gray-200">
                            {logs.map((log) => (
                                <tr key={log.id} className="hover:bg-gray-50 transition-colors">
                                    <td className="px-6 py-4 whitespace-nowrap">
                                        <div className="flex items-center gap-2">
                                            {getStatusIcon(log.status)}
                                            <span className={`text-xs font-bold uppercase ${log.status.toLowerCase() === 'sent' ? 'text-green-700' : 'text-red-700'
                                                }`}>
                                                {log.status}
                                            </span>
                                        </div>
                                    </td>
                                    <td className="px-6 py-4 whitespace-nowrap">
                                        <div className="text-sm font-medium text-gray-900">{log.recipient_email}</div>
                                        <div className="text-xs text-gray-500">{log.username || 'System'}</div>
                                    </td>
                                    <td className="px-6 py-4">
                                        <div className="text-sm text-gray-900 line-clamp-1">{log.subject}</div>
                                        <div className="text-xs text-vulncheck-blue font-mono">
                                            {log.cve_id} • {log.asset_hostname}
                                        </div>
                                    </td>
                                    <td className="px-6 py-4 whitespace-nowrap text-sm text-gray-500">
                                        {format(new Date(log.sent_at), 'dd.MM.yyyy HH:mm')}
                                    </td>
                                    <td className="px-6 py-4 whitespace-nowrap text-right text-sm font-medium">
                                        <button
                                            onClick={() => setPreviewLog(log)}
                                            className="text-vulncheck-blue hover:text-blue-900 flex items-center gap-1 ml-auto"
                                        >
                                            <EyeIcon className="h-4 w-4" />
                                            Preview
                                        </button>
                                    </td>
                                </tr>
                            ))}
                            {logs.length === 0 && (
                                <tr>
                                    <td colSpan={5} className="px-6 py-12 text-center text-gray-500">
                                        No notifications logged yet.
                                    </td>
                                </tr>
                            )}
                        </tbody>
                    </table>
                </div>
            )}

            {/* Email Preview Modal */}
            {previewLog && (
                <div className="fixed inset-0 z-50 overflow-y-auto">
                    <div className="flex items-center justify-center min-h-screen pt-4 px-4 pb-20 text-center sm:block sm:p-0">
                        <div className="fixed inset-0 transition-opacity" aria-hidden="true" onClick={() => setPreviewLog(null)}>
                            <div className="absolute inset-0 bg-gray-500 opacity-75"></div>
                        </div>

                        <div className="inline-block align-bottom bg-white rounded-lg text-left overflow-hidden shadow-2xl transform transition-all sm:my-8 sm:align-middle sm:max-w-4xl sm:w-full relative z-10 border border-gray-200">
                            <div className="bg-white px-6 py-4 border-b border-gray-100 flex items-center justify-between">
                                <div className="flex items-center gap-3">
                                    <div className="bg-vulncheck-blue/10 p-2 rounded-lg">
                                        <EnvelopeIcon className="h-6 w-6 text-vulncheck-blue" />
                                    </div>
                                    <h3 className="text-xl font-bold text-gray-900">Email Transmission Preview</h3>
                                </div>
                                <button
                                    onClick={() => setPreviewLog(null)}
                                    className="text-gray-400 hover:text-gray-600 hover:bg-gray-100 p-2 rounded-full transition-all"
                                >
                                    <XMarkIcon className="h-6 w-6" />
                                </button>
                            </div>
                            <div className="px-6 py-6 bg-white">
                                <div className="space-y-3 mb-8 bg-gray-50 p-4 rounded-xl border border-gray-100">
                                    <div className="flex text-sm">
                                        <span className="w-24 font-bold text-gray-500 uppercase tracking-wider text-[10px] self-center">From</span>
                                        <span className="text-gray-900 font-medium">VulnCheck Security Operations Center &lt;notifications@vulncheck.io&gt;</span>
                                    </div>
                                    <div className="flex text-sm">
                                        <span className="w-24 font-bold text-gray-500 uppercase tracking-wider text-[10px] self-center">To</span>
                                        <span className="text-gray-900 font-medium">{previewLog.recipient_email}</span>
                                    </div>
                                    <div className="flex text-sm">
                                        <span className="w-24 font-bold text-gray-500 uppercase tracking-wider text-[10px] self-center">Subject</span>
                                        <span className="text-gray-900 font-bold">{previewLog.subject}</span>
                                    </div>
                                </div>
                                <div className="bg-white rounded-xl overflow-hidden border border-gray-200 shadow-inner">
                                    {previewLog.message_body ? (
                                        <div className="w-full h-[600px] overflow-hidden bg-white">
                                            <iframe
                                                srcDoc={previewLog.message_body}
                                                className="w-full h-full border-0"
                                                title="Email Body Preview"
                                            />
                                        </div>
                                    ) : (
                                        <div className="text-center py-20 text-gray-400 italic bg-gray-50">
                                            <EnvelopeIcon className="h-12 w-12 mx-auto mb-4 opacity-20" />
                                            No message body content archived for this notification.
                                        </div>
                                    )}
                                </div>
                            </div>
                            <div className="bg-gray-50 px-6 py-4 sm:flex sm:flex-row-reverse gap-3 border-t border-gray-100">
                                <button
                                    type="button"
                                    className="w-full inline-flex justify-center rounded-lg border border-transparent shadow-sm px-6 py-2.5 bg-vulncheck-blue text-sm font-bold text-white hover:bg-blue-700 transition-all sm:w-auto"
                                    onClick={() => setPreviewLog(null)}
                                >
                                    Done
                                </button>
                            </div>
                        </div>
                    </div>
                </div>
            )}
        </div>
    );
}
