"use client";

import { useEffect, useState } from "react";
import { Mail, AlertCircle, CheckCircle, Clock, RefreshCw } from "lucide-react";

export default function EmailsSettingsPage() {
    const [queue, setQueue] = useState<any[]>([]);
    const [logs, setLogs] = useState<any[]>([]);
    const [loading, setLoading] = useState(true);
    const [retryingId, setRetryingId] = useState<string | null>(null);

    const fetchData = async () => {
        setLoading(true);
        try {
            const queueRes = await fetch('/api/admin/emails?type=queue');
            const queueData = await queueRes.json();
            if (queueData.data) setQueue(queueData.data);

            const logsRes = await fetch('/api/admin/emails?type=logs');
            const logsData = await logsRes.json();
            if (logsData.data) setLogs(logsData.data);
        } catch (error) {
            console.error("Error fetching emails:", error);
        } finally {
            setLoading(false);
        }
    };

    useEffect(() => {
        fetchData();
    }, []);

    const handleRetry = async (id: string) => {
        setRetryingId(id);
        try {
            const res = await fetch(`/api/admin/emails/${id}/retry`, { method: 'POST' });
            if (res.ok) {
                // Refresh data
                await fetchData();
            }
        } catch (error) {
            console.error("Error retrying email:", error);
        } finally {
            setRetryingId(null);
        }
    };

    if (loading) {
        return <div className="text-neutral-400">Loading email metrics...</div>;
    }

    const unhandledFailures = queue.filter(q => q.status === 'FAILED');

    return (
        <div className="space-y-8">
            <div className="flex justify-between items-center">
                <div>
                    <h1 className="text-2xl font-bold text-white tracking-tight">Email Delivery Health</h1>
                    <p className="text-sm text-neutral-400 mt-1">
                        Monitor outgoing transactional emails and retry failed ones.
                    </p>
                </div>
                <button
                    onClick={fetchData}
                    className="flex items-center gap-2 bg-neutral-800 hover:bg-neutral-700 text-white px-4 py-2 rounded-md font-medium text-sm transition-colors border border-neutral-700"
                >
                    <RefreshCw className="w-4 h-4" />
                    Refresh
                </button>
            </div>

            {/* Failed Emails Alert */}
            {unhandledFailures.length > 0 && (
                <div className="bg-red-900/20 border border-red-900/50 rounded-lg p-6">
                    <div className="flex items-start gap-4">
                        <AlertCircle className="w-6 h-6 text-red-500 mt-1 flex-shrink-0" />
                        <div>
                            <h3 className="text-white font-medium text-lg">Failed Emails Detected</h3>
                            <p className="text-neutral-400 mt-1 text-sm">
                                {unhandledFailures.length} emails have failed to send after maximum retries. Please investigate and retry manually.
                            </p>

                            <div className="mt-4 space-y-3">
                                {unhandledFailures.map(failure => (
                                    <div key={failure.id} className="bg-neutral-900/50 p-4 rounded-md border border-red-900/30 flex items-center justify-between">
                                        <div>
                                            <div className="flex items-center gap-2">
                                                <span className="text-white font-medium">{failure.to}</span>
                                                <span className="text-xs bg-red-500/10 text-red-500 px-2 py-0.5 rounded-full uppercase tracking-wider">{failure.type}</span>
                                            </div>
                                            <p className="text-xs text-neutral-500 mt-1 font-mono">{failure.last_error}</p>
                                        </div>
                                        <button
                                            onClick={() => handleRetry(failure.id)}
                                            disabled={retryingId === failure.id}
                                            className="px-3 py-1.5 bg-neutral-800 hover:bg-neutral-700 text-white text-xs rounded border border-neutral-700 transition"
                                        >
                                            {retryingId === failure.id ? 'Retrying...' : 'Retry Now'}
                                        </button>
                                    </div>
                                ))}
                            </div>
                        </div>
                    </div>
                </div>
            )}

            {/* Email Logs Component */}
            <div>
                <h2 className="text-lg font-medium text-white mb-4">Recent Email Logs</h2>
                <div className="bg-neutral-800 border border-neutral-700 rounded-xl overflow-hidden">
                    {logs.length === 0 ? (
                        <div className="p-8 text-center text-neutral-500">No emails sent yet.</div>
                    ) : (
                        <table className="w-full text-left text-sm text-neutral-400">
                            <thead className="bg-neutral-900/50 text-xs uppercase border-b border-neutral-700/50">
                                <tr>
                                    <th className="px-6 py-4 font-medium text-neutral-300">Recipient</th>
                                    <th className="px-6 py-4 font-medium text-neutral-300">Type</th>
                                    <th className="px-6 py-4 font-medium text-neutral-300">Subject</th>
                                    <th className="px-6 py-4 font-medium text-neutral-300">Sent At</th>
                                    <th className="px-6 py-4 font-medium text-neutral-300">Status</th>
                                </tr>
                            </thead>
                            <tbody className="divide-y divide-neutral-700/50">
                                {logs.map(log => (
                                    <tr key={log.id} className="hover:bg-neutral-700/20 transition-colors">
                                        <td className="px-6 py-4 font-medium text-white">{log.to}</td>
                                        <td className="px-6 py-4">
                                            <span className="bg-neutral-700 px-2 py-1 rounded text-xs">{log.type}</span>
                                        </td>
                                        <td className="px-6 py-4 truncate max-w-[200px]">{log.subject}</td>
                                        <td className="px-6 py-4">{new Date(log.sent_at).toLocaleString()}</td>
                                        <td className="px-6 py-4">
                                            <span className="flex items-center gap-1.5 text-green-400">
                                                <CheckCircle className="w-4 h-4" />
                                                Delivered
                                            </span>
                                        </td>
                                    </tr>
                                ))}
                            </tbody>
                        </table>
                    )}
                </div>
            </div>

            {/* Active Queue Component */}
            <div>
                <h2 className="text-lg font-medium text-white mb-4">Pending Queue</h2>
                <div className="bg-neutral-800 border border-neutral-700 rounded-xl overflow-hidden">
                    {queue.filter(q => q.status === 'PENDING').length === 0 ? (
                        <div className="p-8 text-center text-neutral-500">Queue is empty.</div>
                    ) : (
                        <table className="w-full text-left text-sm text-neutral-400">
                            <thead className="bg-neutral-900/50 text-xs uppercase border-b border-neutral-700/50">
                                <tr>
                                    <th className="px-6 py-4 font-medium text-neutral-300">Recipient</th>
                                    <th className="px-6 py-4 font-medium text-neutral-300">Type</th>
                                    <th className="px-6 py-4 font-medium text-neutral-300">Attempts</th>
                                    <th className="px-6 py-4 font-medium text-neutral-300">Queued At</th>
                                    <th className="px-6 py-4 font-medium text-neutral-300">Status</th>
                                </tr>
                            </thead>
                            <tbody className="divide-y divide-neutral-700/50">
                                {queue.filter(q => q.status === 'PENDING').map(item => (
                                    <tr key={item.id} className="hover:bg-neutral-700/20 transition-colors">
                                        <td className="px-6 py-4 font-medium text-white">{item.to}</td>
                                        <td className="px-6 py-4">
                                            <span className="bg-neutral-700 px-2 py-1 rounded text-xs">{item.type}</span>
                                        </td>
                                        <td className="px-6 py-4">{item.attempts}</td>
                                        <td className="px-6 py-4">{new Date(item.created_at).toLocaleString()}</td>
                                        <td className="px-6 py-4">
                                            <span className="flex items-center gap-1.5 text-amber-400">
                                                <Clock className="w-4 h-4" />
                                                Pending
                                            </span>
                                        </td>
                                    </tr>
                                ))}
                            </tbody>
                        </table>
                    )}
                </div>
            </div>
        </div>
    );
}
