"use client";

import { useState, useEffect, useTransition } from "react";
import { Settings as SettingsIcon, User, Bell, Lock, Trash2, Save, Loader2, FileText, Mail, CheckCircle } from "lucide-react";
import Link from "next/link";
import { TemplateLibrary } from "@/components/ats/TemplateLibrary";
import { updatePersonalInfo, changePassword } from "@/app/actions/profile";

export default function SettingsPage() {
    const [activeTab, setActiveTab] = useState("profile");

    // Personal info state
    const [profileMsg, setProfileMsg] = useState<{ type: "success" | "error"; text: string } | null>(null);
    const [isProfilePending, startProfileTransition] = useTransition();
    const handleSaveProfile = (e: React.FormEvent<HTMLFormElement>) => {
        e.preventDefault();
        setProfileMsg(null);
        const fd = new FormData(e.currentTarget);
        startProfileTransition(async () => {
            const result = await updatePersonalInfo(fd);
            if (result?.error) setProfileMsg({ type: "error", text: result.error });
            else setProfileMsg({ type: "success", text: "Personal information saved!" });
        });
    };

    // Password change state
    const [pwMsg, setPwMsg] = useState<{ type: "success" | "error"; text: string } | null>(null);
    const [isPasswordPending, startPasswordTransition] = useTransition();
    const handleChangePassword = (e: React.FormEvent<HTMLFormElement>) => {
        e.preventDefault();
        setPwMsg(null);
        const fd = new FormData(e.currentTarget);
        startPasswordTransition(async () => {
            const result = await changePassword(fd);
            if (result?.error) setPwMsg({ type: "error", text: result.error });
            else { setPwMsg({ type: "success", text: "Password updated successfully!" }); (e.target as HTMLFormElement).reset(); }
        });
    };

    // Notification Settings State
    type NotifSetting = {
        category: string;
        in_app: boolean;
        email: string;
        sms: boolean;
        push: boolean;
    };
    const [notifSettings, setNotifSettings] = useState<NotifSetting[]>([]);
    const [isNotifLoading, setIsNotifLoading] = useState(false);
    const [isNotifSaving, setIsNotifSaving] = useState(false);

    useEffect(() => {
        if (activeTab === "notifications") {
            const fetchNotifSettings = async () => {
                setIsNotifLoading(true);
                try {
                    const res = await fetch("/api/user/settings/notifications");
                    if (res.ok) {
                        const data = await res.json();
                        if (Array.isArray(data)) {
                            setNotifSettings(data);
                        }
                    }
                } catch (error) {
                    console.error("Failed to fetch notification settings:", error);
                } finally {
                    setIsNotifLoading(false);
                }
            };
            fetchNotifSettings();
        }
    }, [activeTab]);

    const handleSaveNotifications = async () => {
        setIsNotifSaving(true);
        try {
            await Promise.all(
                notifSettings.map(setting =>
                    fetch("/api/user/settings/notifications", {
                        method: "PUT",
                        headers: { "Content-Type": "application/json" },
                        body: JSON.stringify(setting)
                    })
                )
            );
            console.log("Settings saved!");
            // Optional: show a toast notification here
        } catch (error) {
            console.error("Failed to save settings:", error);
        } finally {
            setIsNotifSaving(false);
        }
    };

    return (
        <div className="space-y-6">
            {/* Header */}
            <div>
                <h1 className="text-3xl font-bold text-slate-900 flex items-center gap-2">
                    <SettingsIcon className="h-8 w-8 text-primary" />
                    Settings
                </h1>
                <p className="text-slate-600 mt-2">
                    Manage your account preferences and settings
                </p>
            </div>

            {/* Tabs */}
            <div className="flex items-center gap-2 border-b border-slate-200">
                <button
                    onClick={() => setActiveTab("profile")}
                    className={`flex items-center gap-2 px-4 py-3 font-semibold border-b-2 transition-colors ${activeTab === "profile"
                        ? "border-primary text-primary"
                        : "border-transparent text-slate-600 hover:text-slate-900"
                        }`}
                >
                    <User className="h-4 w-4" />
                    Profile
                </button>
                <button
                    onClick={() => setActiveTab("notifications")}
                    className={`flex items-center gap-2 px-4 py-3 font-semibold border-b-2 transition-colors ${activeTab === "notifications"
                        ? "border-primary text-primary"
                        : "border-transparent text-slate-600 hover:text-slate-900"
                        }`}
                >
                    <Bell className="h-4 w-4" />
                    Notifications
                </button>
                <button
                    onClick={() => setActiveTab("security")}
                    className={`flex items-center gap-2 px-4 py-3 font-semibold border-b-2 transition-colors ${activeTab === "security"
                        ? "border-primary text-primary"
                        : "border-transparent text-slate-600 hover:text-slate-900"
                        }`}
                >
                    <Lock className="h-4 w-4" />
                    Security
                </button>
                <button
                    onClick={() => setActiveTab("templates")}
                    className={`flex items-center gap-2 px-4 py-3 font-semibold border-b-2 transition-colors ${activeTab === "templates"
                        ? "border-primary text-primary"
                        : "border-transparent text-slate-600 hover:text-slate-900"
                        }`}
                >
                    <FileText className="h-4 w-4" />
                    Templates
                </button>
                <Link
                    href="/dashboard/settings/email-preferences"
                    className="flex items-center gap-2 px-4 py-3 font-semibold border-b-2 border-transparent text-slate-600 hover:text-slate-900 transition-colors"
                >
                    <Mail className="h-4 w-4" />
                    Email Preferences
                </Link>
            </div>

            {activeTab === "profile" && (
                <div className="space-y-6">
                    <div className="rounded-2xl border border-slate-100 bg-white p-6 shadow-sm">
                        <h2 className="font-bold text-slate-900 mb-4">Personal Information</h2>
                        <form onSubmit={handleSaveProfile} className="space-y-4">
                            <div className="grid grid-cols-2 gap-4">
                                <div>
                                    <label className="block text-sm font-semibold text-slate-700 mb-2">First Name</label>
                                    <input name="first_name" type="text" placeholder="First Name"
                                        className="w-full rounded-xl border border-slate-200 px-4 py-3 outline-none focus:border-primary focus:ring-1 focus:ring-primary/20 transition-all text-sm" />
                                </div>
                                <div>
                                    <label className="block text-sm font-semibold text-slate-700 mb-2">Last Name</label>
                                    <input name="last_name" type="text" placeholder="Last Name"
                                        className="w-full rounded-xl border border-slate-200 px-4 py-3 outline-none focus:border-primary focus:ring-1 focus:ring-primary/20 transition-all text-sm" />
                                </div>
                            </div>
                            {profileMsg && (
                                <div className={`flex items-center gap-2 text-sm rounded-lg px-3 py-2 ${profileMsg.type === "success" ? "bg-emerald-50 text-emerald-700 border border-emerald-200" : "bg-red-50 text-red-700 border border-red-200"}`}>
                                    {profileMsg.type === "success" && <CheckCircle className="w-4 h-4" />}
                                    {profileMsg.text}
                                </div>
                            )}
                            <button type="submit" disabled={isProfilePending}
                                className="flex items-center gap-2 px-6 py-3 bg-primary text-white rounded-xl font-semibold hover:bg-blue-700 transition-colors disabled:opacity-50">
                                {isProfilePending ? <><Loader2 className="h-4 w-4 animate-spin" /> Saving...</> : <><Save className="h-4 w-4" /> Save Changes</>}
                            </button>
                        </form>
                    </div>
                </div>
            )}

            {/* Notification Settings */}
            {activeTab === "notifications" && (
                <div className="space-y-6">
                    {isNotifLoading ? (
                        <div className="flex justify-center p-12">
                            <Loader2 className="h-8 w-8 text-primary animate-spin" />
                        </div>
                    ) : (
                        <>
                            <div className="rounded-2xl border border-slate-100 bg-white p-6 shadow-sm">
                                <h2 className="font-bold text-slate-900 mb-4">Email Notifications</h2>
                                <div className="space-y-4">
                                    <NotificationToggle
                                        label="Application Updates"
                                        description="Receive emails when your application status changes"
                                        checked={notifSettings.find(s => s.category === 'applications')?.email === 'instant'}
                                        onChange={(checked) => setNotifSettings(s => s.map(setting => setting.category === 'applications' ? { ...setting, email: checked ? 'instant' : 'off' } : setting))}
                                    />
                                    <NotificationToggle
                                        label="Job Alerts"
                                        description="Get notified about new jobs matching your profile"
                                        checked={notifSettings.find(s => s.category === 'jobs')?.email === 'instant'}
                                        onChange={(checked) => setNotifSettings(s => s.map(setting => setting.category === 'jobs' ? { ...setting, email: checked ? 'instant' : 'off' } : setting))}
                                    />
                                    <NotificationToggle
                                        label="Messages"
                                        description="Receive emails when you get new platform messages"
                                        checked={notifSettings.find(s => s.category === 'messages')?.email === 'instant'}
                                        onChange={(checked) => setNotifSettings(s => s.map(setting => setting.category === 'messages' ? { ...setting, email: checked ? 'instant' : 'off' } : setting))}
                                    />
                                    <NotificationToggle
                                        label="Security Alerts"
                                        description="Emails regarding account security and sign ins"
                                        checked={notifSettings.find(s => s.category === 'security')?.email === 'instant'}
                                        onChange={(checked) => setNotifSettings(s => s.map(setting => setting.category === 'security' ? { ...setting, email: checked ? 'instant' : 'off' } : setting))}
                                    />
                                </div>
                            </div>

                            <div className="rounded-2xl border border-slate-100 bg-white p-6 shadow-sm">
                                <h2 className="font-bold text-slate-900 mb-4" id="alerts">Push Notifications</h2>
                                <div className="space-y-4">
                                    <NotificationToggle
                                        label="Application Updates"
                                        description="On-device alerts for your applications"
                                        checked={notifSettings.find(s => s.category === 'applications')?.push || false}
                                        onChange={(checked) => setNotifSettings(s => s.map(setting => setting.category === 'applications' ? { ...setting, push: checked } : setting))}
                                    />
                                    <NotificationToggle
                                        label="Job Alerts"
                                        description="Instant alerts for hot new jobs"
                                        checked={notifSettings.find(s => s.category === 'jobs')?.push || false}
                                        onChange={(checked) => setNotifSettings(s => s.map(setting => setting.category === 'jobs' ? { ...setting, push: checked } : setting))}
                                    />
                                    <NotificationToggle
                                        label="Direct Messages"
                                        description="On-device alerts for chat messages"
                                        checked={notifSettings.find(s => s.category === 'messages')?.push || false}
                                        onChange={(checked) => setNotifSettings(s => s.map(setting => setting.category === 'messages' ? { ...setting, push: checked } : setting))}
                                    />
                                </div>
                            </div>

                            <button
                                onClick={handleSaveNotifications}
                                disabled={isNotifSaving}
                                className="flex items-center gap-2 px-6 py-3 bg-primary text-white rounded-xl font-semibold hover:bg-blue-700 transition-colors disabled:opacity-70"
                            >
                                {isNotifSaving ? <Loader2 className="h-4 w-4 animate-spin" /> : <Save className="h-4 w-4" />}
                                {isNotifSaving ? "Saving..." : "Save Preferences"}
                            </button>
                        </>
                    )}
                </div>
            )}

            {/* Security Settings */}
            {activeTab === "security" && (
                <div className="space-y-6">
                    <div className="rounded-2xl border border-slate-100 bg-white p-6 shadow-sm">
                        <h2 className="font-bold text-slate-900 mb-4">Change Password</h2>
                        <form onSubmit={handleChangePassword} className="space-y-4">
                            <div>
                                <label className="block text-sm font-semibold text-slate-700 mb-2">Current Password</label>
                                <input name="current_password" type="password" required
                                    className="w-full rounded-xl border border-slate-200 px-4 py-3 outline-none focus:border-primary focus:ring-1 focus:ring-primary/20 transition-all text-sm"
                                    placeholder="••••••••" />
                            </div>
                            <div>
                                <label className="block text-sm font-semibold text-slate-700 mb-2">New Password</label>
                                <input name="new_password" type="password" required minLength={8}
                                    className="w-full rounded-xl border border-slate-200 px-4 py-3 outline-none focus:border-primary focus:ring-1 focus:ring-primary/20 transition-all text-sm"
                                    placeholder="At least 8 characters" />
                            </div>
                            <div>
                                <label className="block text-sm font-semibold text-slate-700 mb-2">Confirm New Password</label>
                                <input name="confirm_password" type="password" required minLength={8}
                                    className="w-full rounded-xl border border-slate-200 px-4 py-3 outline-none focus:border-primary focus:ring-1 focus:ring-primary/20 transition-all text-sm"
                                    placeholder="Repeat your new password" />
                            </div>
                            {pwMsg && (
                                <div className={`flex items-center gap-2 text-sm rounded-lg px-3 py-2 ${pwMsg.type === "success" ? "bg-emerald-50 text-emerald-700 border border-emerald-200" : "bg-red-50 text-red-700 border border-red-200"}`}>
                                    {pwMsg.type === "success" && <CheckCircle className="w-4 h-4" />}
                                    {pwMsg.text}
                                </div>
                            )}
                            <button type="submit" disabled={isPasswordPending}
                                className="flex items-center gap-2 px-6 py-3 bg-primary text-white rounded-xl font-semibold hover:bg-blue-700 transition-colors disabled:opacity-50">
                                {isPasswordPending ? <><Loader2 className="h-4 w-4 animate-spin" /> Updating...</> : "Update Password"}
                            </button>
                        </form>
                    </div>

                    <div className="rounded-2xl border border-red-100 bg-red-50 p-6">
                        <h2 className="font-bold text-red-900 mb-2 flex items-center gap-2">
                            <Trash2 className="h-5 w-5" />
                            Danger Zone
                        </h2>
                        <p className="text-sm text-red-700 mb-4">
                            Once you delete your account, there is no going back. Please be certain.
                        </p>
                        <button className="px-6 py-3 bg-red-600 text-white rounded-xl font-semibold hover:bg-red-700 transition-colors">
                            Delete Account
                        </button>
                    </div>
                </div>
            )}
        </div>
    );
}

function NotificationToggle({ label, description, checked, onChange }: { label: string; description: string; checked: boolean; onChange: (c: boolean) => void }) {
    return (
        <div className="flex items-center justify-between py-3 border-b border-slate-100 last:border-0">
            <div>
                <p className="font-semibold text-slate-900">{label}</p>
                <p className="text-sm text-slate-500 mt-0.5">{description}</p>
            </div>
            <button
                onClick={() => onChange(!checked)}
                className={`relative w-12 h-6 rounded-full transition-colors ${checked ? 'bg-primary' : 'bg-slate-300'
                    }`}
            >
                <span
                    className={`absolute top-0.5 left-0.5 h-5 w-5 rounded-full bg-white transition-transform ${checked ? 'translate-x-6' : 'translate-x-0'
                        }`}
                />
            </button>
        </div>
    );
}
