"use client";

import { useState, useEffect, useTransition } from "react";
import { Mail, Search, Trash2, Loader2, Shield, AlertCircle, RefreshCw } from "lucide-react";

type SuppressionEntry = {
    id: string;
    email: string;
    reason: string;
    is_permanent: boolean;
    suppressed_at: string;
};

export default function AdminEmailPreferencesPage() {
    const [suppressionList, setSuppressionList] = useState<SuppressionEntry[]>([]);
    const [loading, setLoading] = useState(true);
    const [searchQuery, setSearchQuery] = useState("");
    const [isPending, startTransition] = useTransition();
    const [stats, setStats] = useState({ total: 0, unsubscribed: 0, bounced: 0, complaints: 0 });

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

    async function loadData() {
        setLoading(true);
        try {
            const res = await fetch("/api/admin/email-preferences");
            if (res.ok) {
                const data = await res.json();
                setSuppressionList(data.suppressionList || []);
                setStats(data.stats || { total: 0, unsubscribed: 0, bounced: 0, complaints: 0 });
            }
        } catch (e) {
            console.error("Failed to load admin email preferences:", e);
        }
        setLoading(false);
    }

    async function handleRemoveSuppression(id: string) {
        if (!confirm("Remove this email from the suppression list? The user will start receiving emails again.")) return;
        startTransition(async () => {
            try {
                await fetch(`/api/admin/email-preferences/${id}`, { method: "DELETE" });
                setSuppressionList(prev => prev.filter(s => s.id !== id));
            } catch (e) {
                console.error("Failed to remove suppression:", e);
            }
        });
    }

    const filteredList = suppressionList.filter(s =>
        s.email.toLowerCase().includes(searchQuery.toLowerCase())
    );

    return (
        <div className="space-y-6">
            {/* Header */}
            <div>
                <h1 className="text-2xl font-bold text-slate-900 flex items-center gap-2">
                    <Mail className="h-6 w-6 text-primary" />
                    Email Preference Management
                </h1>
                <p className="text-sm text-slate-500 mt-1">Manage platform-wide email suppression and monitor delivery health</p>
            </div>

            {/* Stats Cards */}
            <div className="grid grid-cols-2 md:grid-cols-4 gap-4">
                <StatCard icon={<Mail className="h-5 w-5 text-blue-600" />} label="Total Suppressed" value={stats.total} color="blue" />
                <StatCard icon={<AlertCircle className="h-5 w-5 text-amber-600" />} label="Unsubscribed" value={stats.unsubscribed} color="amber" />
                <StatCard icon={<Shield className="h-5 w-5 text-red-600" />} label="Bounced" value={stats.bounced} color="red" />
                <StatCard icon={<AlertCircle className="h-5 w-5 text-orange-600" />} label="Complaints" value={stats.complaints} color="orange" />
            </div>

            {/* Suppression List */}
            <div className="rounded-2xl border border-slate-100 bg-white shadow-sm">
                <div className="flex items-center justify-between p-4 border-b border-slate-100">
                    <h2 className="font-bold text-slate-900">Suppression List</h2>
                    <div className="flex items-center gap-2">
                        <div className="relative">
                            <Search className="absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-slate-400" />
                            <input
                                type="text"
                                placeholder="Search email..."
                                value={searchQuery}
                                onChange={(e) => setSearchQuery(e.target.value)}
                                className="pl-9 pr-4 py-2 rounded-lg border border-slate-200 text-sm outline-none focus:border-primary w-64"
                            />
                        </div>
                        <button onClick={loadData} className="p-2 rounded-lg hover:bg-slate-100 transition-colors">
                            <RefreshCw className={`h-4 w-4 text-slate-500 ${loading ? 'animate-spin' : ''}`} />
                        </button>
                    </div>
                </div>

                {loading ? (
                    <div className="flex justify-center p-12">
                        <Loader2 className="h-6 w-6 text-primary animate-spin" />
                    </div>
                ) : filteredList.length === 0 ? (
                    <div className="text-center p-12 text-slate-500 text-sm">
                        {searchQuery ? "No matching emails found" : "No suppressed emails. All clear!"}
                    </div>
                ) : (
                    <div className="divide-y divide-slate-100">
                        {filteredList.map(entry => (
                            <div key={entry.id} className="flex items-center justify-between px-4 py-3 hover:bg-slate-50">
                                <div>
                                    <p className="font-medium text-slate-900 text-sm">{entry.email}</p>
                                    <div className="flex items-center gap-2 mt-0.5">
                                        <span className={`inline-flex items-center text-xs px-2 py-0.5 rounded-full font-medium ${
                                            entry.reason === 'bounce' ? 'bg-red-100 text-red-700' :
                                            entry.reason === 'complaint' ? 'bg-orange-100 text-orange-700' :
                                            'bg-amber-100 text-amber-700'
                                        }`}>
                                            {entry.reason}
                                        </span>
                                        <span className="text-xs text-slate-400">
                                            {new Date(entry.suppressed_at).toLocaleDateString()}
                                        </span>
                                        {entry.is_permanent && (
                                            <span className="text-xs bg-red-100 text-red-600 px-1.5 py-0.5 rounded font-medium">Permanent</span>
                                        )}
                                    </div>
                                </div>
                                <button
                                    onClick={() => handleRemoveSuppression(entry.id)}
                                    disabled={isPending}
                                    className="p-2 rounded-lg text-slate-400 hover:text-red-600 hover:bg-red-50 transition-colors"
                                    title="Remove from suppression list"
                                >
                                    <Trash2 className="h-4 w-4" />
                                </button>
                            </div>
                        ))}
                    </div>
                )}
            </div>
        </div>
    );
}

function StatCard({ icon, label, value, color }: { icon: React.ReactNode; label: string; value: number; color: string }) {
    const bgMap: Record<string, string> = {
        blue: "bg-blue-50", amber: "bg-amber-50", red: "bg-red-50", orange: "bg-orange-50"
    };
    return (
        <div className={`rounded-xl ${bgMap[color] || 'bg-slate-50'} p-4`}>
            <div className="flex items-center gap-2 mb-2">{icon}</div>
            <p className="text-2xl font-bold text-slate-900">{value}</p>
            <p className="text-xs text-slate-500 mt-0.5">{label}</p>
        </div>
    );
}
