"use client";

import { useState, useEffect, useTransition } from "react";
import { Mail, Bell, Clock, Pause, Play, Shield, AlertTriangle, Save, Loader2, ChevronDown, ArrowLeft } from "lucide-react";
import Link from "next/link";
import {
    getEmailPreferences,
    updateGlobalEmailPreferences,
    updateCategoryPreference,
    pauseAllEmails,
    resumeAllEmails,
    unsubscribeFromAll,
    resubscribeAll,
    getRecentEmails,
} from "@/app/actions/emailPreferenceActions";
import { pauseJobAlert, resumeJobAlert, deleteJobAlert } from "@/app/actions/jobAlertActions";

type CategoryPref = {
    id: string;
    label: string;
    description: string;
    enabled: boolean;
    frequency: string;
    in_app: boolean;
    sms: boolean;
    push: boolean;
    isRequired: boolean;
};

type GlobalPrefs = {
    unsubscribed_all: boolean;
    global_pause_until: string | null;
    quiet_hours_start: string | null;
    quiet_hours_end: string | null;
    digest_time: string;
    timezone: string;
};

type JobAlert = {
    id: string;
    name: string;
    alert_frequency: string;
    is_active: boolean;
    paused_until: string | null;
};

export default function EmailPreferencesClient() {
    const [loading, setLoading] = useState(true);
    const [isPending, startTransition] = useTransition();
    const [saveMessage, setSaveMessage] = useState<string | null>(null);
    const [global, setGlobal] = useState<GlobalPrefs>({
        unsubscribed_all: false, global_pause_until: null,
        quiet_hours_start: null, quiet_hours_end: null,
        digest_time: "09:00", timezone: "Africa/Lagos"
    });
    const [categories, setCategories] = useState<CategoryPref[]>([]);
    const [jobAlerts, setJobAlerts] = useState<JobAlert[]>([]);
    const [recentEmails, setRecentEmails] = useState<any[]>([]);
    const [pauseDuration, setPauseDuration] = useState("1_week");

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

    async function loadPreferences() {
        setLoading(true);
        const [prefResult, recentResult] = await Promise.all([
            getEmailPreferences(),
            getRecentEmails()
        ]);
        
        if (prefResult.success && prefResult.data) {
            setGlobal(prefResult.data.global as GlobalPrefs);
            setCategories(prefResult.data.categories as CategoryPref[]);
            setJobAlerts(prefResult.data.jobAlerts as JobAlert[]);
        }
        
        if (recentResult.success && recentResult.data) {
            setRecentEmails(recentResult.data);
        }
        setLoading(false);
    }

    function showSaveMsg(msg: string) {
        setSaveMessage(msg);
        setTimeout(() => setSaveMessage(null), 3000);
    }

    async function handleCategoryToggle(categoryId: string, enabled: boolean) {
        startTransition(async () => {
            await updateCategoryPreference(categoryId, { email: enabled ? 'instant' : 'off' });
            setCategories(prev => prev.map(c => c.id === categoryId ? { ...c, enabled } : c));
            showSaveMsg("Preference updated");
        });
    }

    async function handleCategoryFrequency(categoryId: string, frequency: string) {
        startTransition(async () => {
            await updateCategoryPreference(categoryId, { email: frequency });
            setCategories(prev => prev.map(c => c.id === categoryId ? { ...c, frequency, enabled: frequency !== 'off' } : c));
            showSaveMsg("Frequency updated");
        });
    }

    async function handlePauseAll() {
        const until = new Date();
        if (pauseDuration === "1_week") until.setDate(until.getDate() + 7);
        else if (pauseDuration === "2_weeks") until.setDate(until.getDate() + 14);
        else if (pauseDuration === "1_month") until.setMonth(until.getMonth() + 1);

        startTransition(async () => {
            await pauseAllEmails(until);
            setGlobal(prev => ({ ...prev, global_pause_until: until.toISOString() }));
            showSaveMsg(`Emails paused until ${until.toLocaleDateString()}`);
        });
    }

    async function handleResumeAll() {
        startTransition(async () => {
            await resumeAllEmails();
            setGlobal(prev => ({ ...prev, global_pause_until: null }));
            showSaveMsg("Emails resumed");
        });
    }

    async function handleUnsubscribeAll() {
        if (!confirm("Are you sure? You'll stop receiving ALL emails except critical security alerts. This cannot be easily undone.")) return;
        startTransition(async () => {
            await unsubscribeFromAll();
            setGlobal(prev => ({ ...prev, unsubscribed_all: true }));
            showSaveMsg("Unsubscribed from all emails");
        });
    }

    async function handleResubscribe() {
        startTransition(async () => {
            await resubscribeAll();
            setGlobal(prev => ({ ...prev, unsubscribed_all: false }));
            showSaveMsg("Re-subscribed to emails");
        });
    }

    async function handleSaveGlobal() {
        startTransition(async () => {
            await updateGlobalEmailPreferences({
                quietHoursStart: global.quiet_hours_start,
                quietHoursEnd: global.quiet_hours_end,
                digestTime: global.digest_time,
                timezone: global.timezone,
            });
            showSaveMsg("Settings saved");
        });
    }

    async function handlePauseAlert(alertId: string) {
        startTransition(async () => {
            await pauseJobAlert(alertId);
            setJobAlerts(prev => prev.map(a => a.id === alertId ? { ...a, is_active: false } : a));
            showSaveMsg("Alert paused");
        });
    }

    async function handleResumeAlert(alertId: string) {
        startTransition(async () => {
            await resumeJobAlert(alertId);
            setJobAlerts(prev => prev.map(a => a.id === alertId ? { ...a, is_active: true, paused_until: null } : a));
            showSaveMsg("Alert resumed");
        });
    }

    async function handleDeleteAlert(alertId: string) {
        if (!confirm("Delete this job alert?")) return;
        startTransition(async () => {
            await deleteJobAlert(alertId);
            setJobAlerts(prev => prev.filter(a => a.id !== alertId));
            showSaveMsg("Alert deleted");
        });
    }

    if (loading) {
        return (
            <div className="flex justify-center items-center p-20">
                <Loader2 className="h-8 w-8 text-primary animate-spin" />
            </div>
        );
    }

    const isPaused = global.global_pause_until && new Date(global.global_pause_until) > new Date();

    return (
        <div className="max-w-3xl mx-auto space-y-6">
            {/* Header */}
            <div className="flex items-center gap-3">
                <Link href="/dashboard/settings" className="p-2 rounded-lg hover:bg-slate-100 transition-colors">
                    <ArrowLeft className="h-5 w-5 text-slate-600" />
                </Link>
                <div>
                    <h1 className="text-2xl font-bold text-slate-900 flex items-center gap-2">
                        <Mail className="h-6 w-6 text-primary" />
                        Email Preferences
                    </h1>
                    <p className="text-sm text-slate-500 mt-1">Control which emails you receive and how often</p>
                </div>
            </div>

            {/* Save message toast */}
            {saveMessage && (
                <div className="fixed top-4 right-4 z-50 bg-emerald-500 text-white px-4 py-2 rounded-xl shadow-lg animate-in slide-in-from-top-2 text-sm font-medium">
                    ✓ {saveMessage}
                </div>
            )}

            {/* Unsubscribed banner */}
            {global.unsubscribed_all && (
                <div className="rounded-xl bg-amber-50 border border-amber-200 p-4 flex items-start gap-3">
                    <AlertTriangle className="h-5 w-5 text-amber-600 mt-0.5 shrink-0" />
                    <div>
                        <p className="font-semibold text-amber-900">You&apos;re unsubscribed from all emails</p>
                        <p className="text-sm text-amber-700 mt-1">You won&apos;t receive any emails except critical security alerts.</p>
                        <button
                            onClick={handleResubscribe}
                            disabled={isPending}
                            className="mt-2 text-sm font-semibold text-primary hover:underline"
                        >
                            Re-subscribe to emails
                        </button>
                    </div>
                </div>
            )}

            {/* Paused banner */}
            {isPaused && !global.unsubscribed_all && (
                <div className="rounded-xl bg-blue-50 border border-blue-200 p-4 flex items-start gap-3">
                    <Pause className="h-5 w-5 text-blue-600 mt-0.5 shrink-0" />
                    <div>
                        <p className="font-semibold text-blue-900">Emails paused</p>
                        <p className="text-sm text-blue-700 mt-1">Until {new Date(global.global_pause_until!).toLocaleDateString()}</p>
                        <button
                            onClick={handleResumeAll}
                            disabled={isPending}
                            className="mt-2 text-sm font-semibold text-primary hover:underline flex items-center gap-1"
                        >
                            <Play className="h-3.5 w-3.5" /> Resume now
                        </button>
                    </div>
                </div>
            )}

            {/* Section 1: Critical Emails */}
            <div className="rounded-2xl border border-slate-100 bg-white p-6 shadow-sm">
                <div className="flex items-center gap-2 mb-4">
                    <Shield className="h-5 w-5 text-emerald-600" />
                    <h2 className="font-bold text-slate-900">Critical Emails</h2>
                    <span className="text-xs bg-emerald-100 text-emerald-700 px-2 py-0.5 rounded-full font-medium">Always On</span>
                </div>
                <p className="text-sm text-slate-500 mb-3">These emails ensure your account security and core functionality. They cannot be disabled.</p>
                <ul className="text-sm text-slate-600 space-y-1.5 pl-4">
                    <li>• Email verification & password resets</li>
                    <li>• Security alerts & login notifications</li>
                    <li>• Interview confirmations</li>
                    <li>• Application receipts</li>
                </ul>
            </div>

            {/* Section 2: Category Preferences */}
            <div className="rounded-2xl border border-slate-100 bg-white p-6 shadow-sm">
                <div className="flex items-center gap-2 mb-4">
                    <Bell className="h-5 w-5 text-primary" />
                    <h2 className="font-bold text-slate-900">Notification Emails</h2>
                </div>
                <div className="divide-y divide-slate-100">
                    {categories.map(cat => (
                        <div key={cat.id} className="flex items-center justify-between py-4 first:pt-0 last:pb-0">
                            <div className="flex-1 pr-4">
                                <p className="font-semibold text-slate-900 text-sm">{cat.label}</p>
                                <p className="text-xs text-slate-500 mt-0.5">{cat.description}</p>
                            </div>
                            <div className="flex items-center gap-3">
                                {/* Frequency dropdown */}
                                <div className="relative">
                                    <select
                                        value={cat.enabled ? cat.frequency : 'off'}
                                        onChange={(e) => handleCategoryFrequency(cat.id, e.target.value)}
                                        disabled={cat.isRequired || isPending || global.unsubscribed_all}
                                        className="appearance-none bg-slate-50 border border-slate-200 rounded-lg pl-3 pr-8 py-1.5 text-xs font-medium text-slate-700 cursor-pointer focus:outline-none focus:ring-2 focus:ring-primary/20 disabled:opacity-50 disabled:cursor-not-allowed"
                                    >
                                        <option value="instant">Instant</option>
                                        <option value="daily">Daily Digest</option>
                                        <option value="weekly">Weekly</option>
                                        <option value="off">Off</option>
                                    </select>
                                    <ChevronDown className="absolute right-2 top-1/2 -translate-y-1/2 h-3.5 w-3.5 text-slate-400 pointer-events-none" />
                                </div>
                                {/* Toggle */}
                                <button
                                    onClick={() => handleCategoryToggle(cat.id, !cat.enabled)}
                                    disabled={cat.isRequired || isPending || global.unsubscribed_all}
                                    className={`relative w-10 h-5 rounded-full transition-colors shrink-0 ${
                                        cat.isRequired ? 'bg-emerald-500 cursor-not-allowed' :
                                        cat.enabled ? 'bg-primary' : 'bg-slate-300'
                                    } disabled:opacity-60`}
                                >
                                    <span className={`absolute top-0.5 left-0.5 h-4 w-4 rounded-full bg-white transition-transform shadow-sm ${
                                        cat.enabled || cat.isRequired ? 'translate-x-5' : 'translate-x-0'
                                    }`} />
                                </button>
                            </div>
                        </div>
                    ))}
                </div>
            </div>

            {/* Section 3: Job Alerts */}
            {jobAlerts.length > 0 && (
                <div className="rounded-2xl border border-slate-100 bg-white p-6 shadow-sm">
                    <div className="flex items-center justify-between mb-4">
                        <div className="flex items-center gap-2">
                            <Mail className="h-5 w-5 text-indigo-600" />
                            <h2 className="font-bold text-slate-900">Job Alerts</h2>
                        </div>
                        <Link href="/dashboard/saved" className="text-xs text-primary font-semibold hover:underline">
                            Manage Searches →
                        </Link>
                    </div>
                    <div className="divide-y divide-slate-100">
                        {jobAlerts.map(alert => (
                            <div key={alert.id} className="flex items-center justify-between py-3 first:pt-0 last:pb-0">
                                <div>
                                    <p className="font-semibold text-slate-900 text-sm">{alert.name}</p>
                                    <p className="text-xs text-slate-500 mt-0.5 capitalize">{alert.alert_frequency} • {alert.is_active ? 'Active' : 'Paused'}</p>
                                </div>
                                <div className="flex items-center gap-2">
                                    {alert.is_active ? (
                                        <button onClick={() => handlePauseAlert(alert.id)} disabled={isPending}
                                            className="text-xs font-medium text-slate-600 hover:text-slate-900 px-2 py-1 rounded-lg hover:bg-slate-100 transition-colors"
                                        >Pause</button>
                                    ) : (
                                        <button onClick={() => handleResumeAlert(alert.id)} disabled={isPending}
                                            className="text-xs font-medium text-primary hover:text-blue-700 px-2 py-1 rounded-lg hover:bg-blue-50 transition-colors"
                                        >Resume</button>
                                    )}
                                    <button onClick={() => handleDeleteAlert(alert.id)} disabled={isPending}
                                        className="text-xs font-medium text-red-500 hover:text-red-700 px-2 py-1 rounded-lg hover:bg-red-50 transition-colors"
                                    >Delete</button>
                                </div>
                            </div>
                        ))}
                    </div>
                </div>
            )}

            {/* Section 4: Delivery Settings */}
            <div className="rounded-2xl border border-slate-100 bg-white p-6 shadow-sm">
                <div className="flex items-center gap-2 mb-4">
                    <Clock className="h-5 w-5 text-slate-600" />
                    <h2 className="font-bold text-slate-900">Delivery Settings</h2>
                </div>
                <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                    <div>
                        <label className="block text-xs font-semibold text-slate-600 mb-1.5">Daily Digest Time</label>
                        <input
                            type="time"
                            value={global.digest_time}
                            onChange={(e) => setGlobal(prev => ({ ...prev, digest_time: e.target.value }))}
                            className="w-full rounded-lg border border-slate-200 px-3 py-2 text-sm outline-none focus:border-primary focus:ring-1 focus:ring-primary/20"
                        />
                    </div>
                    <div>
                        <label className="block text-xs font-semibold text-slate-600 mb-1.5">Timezone</label>
                        <select
                            value={global.timezone}
                            onChange={(e) => setGlobal(prev => ({ ...prev, timezone: e.target.value }))}
                            className="w-full rounded-lg border border-slate-200 px-3 py-2 text-sm outline-none focus:border-primary focus:ring-1 focus:ring-primary/20"
                        >
                            <option value="Africa/Lagos">Africa/Lagos (WAT)</option>
                            <option value="America/New_York">America/New_York (EST)</option>
                            <option value="America/Los_Angeles">America/Los_Angeles (PST)</option>
                            <option value="Europe/London">Europe/London (GMT)</option>
                            <option value="Asia/Kolkata">Asia/Kolkata (IST)</option>
                            <option value="Asia/Tokyo">Asia/Tokyo (JST)</option>
                        </select>
                    </div>
                    <div>
                        <label className="block text-xs font-semibold text-slate-600 mb-1.5">Quiet Hours Start</label>
                        <input
                            type="time"
                            value={global.quiet_hours_start || ""}
                            onChange={(e) => setGlobal(prev => ({ ...prev, quiet_hours_start: e.target.value || null }))}
                            className="w-full rounded-lg border border-slate-200 px-3 py-2 text-sm outline-none focus:border-primary focus:ring-1 focus:ring-primary/20"
                        />
                    </div>
                    <div>
                        <label className="block text-xs font-semibold text-slate-600 mb-1.5">Quiet Hours End</label>
                        <input
                            type="time"
                            value={global.quiet_hours_end || ""}
                            onChange={(e) => setGlobal(prev => ({ ...prev, quiet_hours_end: e.target.value || null }))}
                            className="w-full rounded-lg border border-slate-200 px-3 py-2 text-sm outline-none focus:border-primary focus:ring-1 focus:ring-primary/20"
                        />
                    </div>
                </div>
                <button
                    onClick={handleSaveGlobal}
                    disabled={isPending}
                    className="mt-4 flex items-center gap-2 px-5 py-2.5 bg-primary text-white rounded-xl text-sm font-semibold hover:bg-blue-700 transition-colors disabled:opacity-70"
                >
                    {isPending ? <Loader2 className="h-4 w-4 animate-spin" /> : <Save className="h-4 w-4" />}
                    Save Settings
                </button>
            </div>

            {/* Section 5: Pause / Unsubscribe */}
            <div className="rounded-2xl border border-slate-200 bg-slate-50 p-6">
                <h2 className="font-bold text-slate-900 mb-3">Need a break?</h2>
                <div className="flex flex-wrap items-center gap-3 mb-4">
                    <select
                        value={pauseDuration}
                        onChange={(e) => setPauseDuration(e.target.value)}
                        className="rounded-lg border border-slate-200 px-3 py-2 text-sm bg-white"
                    >
                        <option value="1_week">1 week</option>
                        <option value="2_weeks">2 weeks</option>
                        <option value="1_month">1 month</option>
                    </select>
                    <button
                        onClick={handlePauseAll}
                        disabled={isPending}
                        className="flex items-center gap-1.5 px-4 py-2 border border-slate-300 rounded-xl text-sm font-semibold text-slate-700 hover:bg-white transition-colors disabled:opacity-70"
                    >
                        <Pause className="h-3.5 w-3.5" />
                        Pause All Emails
                    </button>
                </div>
                <div className="border-t border-slate-200 pt-4">
                    <p className="text-sm text-slate-500 mb-2">Want to stop all non-essential emails completely?</p>
                    <button
                        onClick={handleUnsubscribeAll}
                        disabled={isPending || global.unsubscribed_all}
                        className="text-sm font-semibold text-red-600 hover:text-red-700 hover:underline disabled:opacity-50"
                    >
                        Unsubscribe from everything
                    </button>
                </div>
            </div>

            {/* Section 6: Recent Emails (Delivery History) */}
            <div className="rounded-2xl border border-slate-100 bg-white p-6 shadow-sm">
                <div className="flex items-center justify-between mb-4">
                    <div className="flex items-center gap-2">
                        <Mail className="h-5 w-5 text-slate-500" />
                        <h2 className="font-bold text-slate-900">Recent Emails</h2>
                    </div>
                </div>
                <p className="text-sm text-slate-500 mb-4">A record of emails sent to you over the last 30 days.</p>
                
                {recentEmails.length === 0 ? (
                    <div className="text-center py-6 border border-dashed border-slate-200 rounded-xl">
                        <Mail className="h-8 w-8 text-slate-300 mx-auto mb-2" />
                        <p className="text-sm font-medium text-slate-600">No recent emails</p>
                    </div>
                ) : (
                    <div className="overflow-x-auto">
                        <table className="w-full text-left text-sm whitespace-nowrap">
                            <thead className="bg-slate-50 text-slate-500">
                                <tr>
                                    <th className="px-4 py-2 font-medium rounded-l-lg">Type</th>
                                    <th className="px-4 py-2 font-medium">To</th>
                                    <th className="px-4 py-2 font-medium">Status</th>
                                    <th className="px-4 py-2 font-medium">Delivery</th>
                                    <th className="px-4 py-2 font-medium rounded-r-lg">Date</th>
                                </tr>
                            </thead>
                            <tbody className="divide-y divide-slate-50">
                                {recentEmails.map((email) => (
                                    <tr key={email.id} className="hover:bg-slate-50/50 transition-colors">
                                        <td className="px-4 py-3 font-medium text-slate-700 capitalize">
                                            {email.type.replace(/_/g, " ")}
                                        </td>
                                        <td className="px-4 py-3 text-slate-500">{email.to}</td>
                                        <td className="px-4 py-3">
                                            <span className={`px-2 py-0.5 rounded-full text-[11px] font-bold ${
                                                email.status === "SENT" ? "bg-emerald-100 text-emerald-700" :
                                                email.status === "FAILED" ? "bg-red-100 text-red-700" :
                                                "bg-amber-100 text-amber-700"
                                            }`}>
                                                {email.status}
                                            </span>
                                        </td>
                                        <td className="px-4 py-3">
                                            <span className={`px-2 py-0.5 rounded-full text-[11px] font-bold ${
                                                email.delivery_status === "delivered" ? "bg-emerald-100 text-emerald-700" :
                                                email.delivery_status === "opened" ? "bg-blue-100 text-blue-700" :
                                                email.delivery_status === "clicked" ? "bg-purple-100 text-purple-700" :
                                                email.delivery_status?.startsWith("bounced") ? "bg-red-100 text-red-700" :
                                                "bg-slate-100 text-slate-600"
                                            }`}>
                                                {email.delivery_status || "unknown"}
                                            </span>
                                        </td>
                                        <td className="px-4 py-3 text-slate-500 text-xs">
                                            {new Date(email.sent_at).toLocaleString()}
                                        </td>
                                    </tr>
                                ))}
                            </tbody>
                        </table>
                    </div>
                )}
            </div>
        </div>
    );
}
