"use client"

import { useState, useEffect } from "react"
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card"
import { Label } from "@/components/ui/label"
import { Switch } from "@/components/ui/switch"
import { Input } from "@/components/ui/input"
import { Textarea } from "@/components/ui/textarea"
import { Button } from "@/components/ui/button"
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs"
import { Separator } from "@/components/ui/separator"
import { usePreferences } from "@/contexts/preferences-context"
import { useAuth } from "@/contexts/auth-context"
import { getApiUrl } from "@/lib/api-config"
import { UserAvatar } from "@/components/ui/user-avatar"
import {
    User,
    Palette,
    Bell,
    Eye,
    Shield,
    Sparkles,
    Check,
    ArrowLeft,
    Lock
} from "lucide-react"
import Link from "next/link"

// Avatar color palette - Jewel Tones with XP unlock tiers
const PRESET_COLORS = [
    // Starter Tier (0 XP) - Always unlocked
    { value: "#0F4C81", name: "Sapphire", tier: "Starter", xpRequired: 0 },
    { value: "#9B111E", name: "Ruby", tier: "Starter", xpRequired: 0 },
    { value: "#50C878", name: "Emerald", tier: "Starter", xpRequired: 0 },
    { value: "#9966CC", name: "Amethyst", tier: "Starter", xpRequired: 0 },
    // Bronze Tier (100 XP)
    { value: "#0D98BA", name: "Topaz", tier: "Bronze", xpRequired: 100 },
    { value: "#E0115F", name: "Rose Quartz", tier: "Bronze", xpRequired: 100 },
    { value: "#082567", name: "Lapis", tier: "Bronze", xpRequired: 100 },
    { value: "#FF7518", name: "Carnelian", tier: "Bronze", xpRequired: 100 },
    // Silver Tier (500 XP)
    { value: "#006B3C", name: "Jade", tier: "Silver", xpRequired: 500 },
    { value: "#1C1C1C", name: "Onyx", tier: "Silver", xpRequired: 500 },
    // Gold Tier (1000 XP)
    { value: "#E6E200", name: "Citrine", tier: "Gold", xpRequired: 1000 },
    { value: "#702963", name: "Garnet", tier: "Gold", xpRequired: 1000 },
]

export default function SettingsPage() {
    const { preferences, updatePreferences, loading } = usePreferences()
    const { user, refreshUser } = useAuth()

    // Profile state
    const [bio, setBio] = useState("")
    const [username, setUsername] = useState("")
    const [profileSaving, setProfileSaving] = useState(false)
    const [profileSaved, setProfileSaved] = useState(false)

    // Avatar state
    const [avatarBgColor, setAvatarBgColor] = useState("#0F4C81")
    const [avatarText, setAvatarText] = useState("")
    const [avatarSaving, setAvatarSaving] = useState(false)
    const [avatarSaved, setAvatarSaved] = useState(false)
    const [avatarError, setAvatarError] = useState("")

    // Privacy state
    const [privacySettings, setPrivacySettings] = useState({
        profile_public: true,
        show_attendance_public: true,
        appear_in_leaderboards: true
    })

    useEffect(() => {
        if (user) {
            const extUser = user as any
            setBio(extUser.bio || "")
            setUsername(extUser.email?.split('@')[0] || "")
            setAvatarBgColor(extUser.avatar_bg_color || "#0F4C81")
            setAvatarText(extUser.avatar_text || "")
            setPrivacySettings({
                profile_public: extUser.profile_public ?? true,
                show_attendance_public: extUser.show_attendance_public ?? true,
                appear_in_leaderboards: extUser.appear_in_leaderboards ?? true
            })
        }
    }, [user])

    const handleSaveProfile = async () => {
        setProfileSaving(true)
        setProfileSaved(false)
        const token = localStorage.getItem("token")
        try {
            await fetch(`${getApiUrl()}/users/me`, {
                method: "PATCH",
                headers: {
                    "Content-Type": "application/json",
                    "Authorization": `Bearer ${token}`
                },
                body: JSON.stringify({ bio, username })
            })
            setProfileSaved(true)
            setTimeout(() => setProfileSaved(false), 2000)
        } catch (e) {
            console.error(e)
        } finally {
            setProfileSaving(false)
        }
    }

    const handleAvatarTextChange = (value: string) => {
        const cleaned = value.replace(/[^A-Za-z0-9]/g, '').slice(0, 3).toUpperCase()
        setAvatarText(cleaned)
        setAvatarError("")
    }

    const handleSaveAvatar = async () => {
        setAvatarSaving(true)
        setAvatarSaved(false)
        setAvatarError("")

        try {
            const token = localStorage.getItem("token")
            const res = await fetch(`${getApiUrl()}/users/me/avatar`, {
                method: "PATCH",
                headers: {
                    "Content-Type": "application/json",
                    Authorization: `Bearer ${token}`,
                },
                body: JSON.stringify({
                    bg_color: avatarBgColor,
                    text: avatarText || null,
                }),
            })

            if (!res.ok) {
                const data = await res.json()
                throw new Error(data.detail || "Failed to save")
            }

            setAvatarSaved(true)
            refreshUser?.()
            setTimeout(() => setAvatarSaved(false), 2000)
        } catch (e: any) {
            setAvatarError(e.message || "Failed to save avatar")
        } finally {
            setAvatarSaving(false)
        }
    }

    const handlePrivacyChange = async (key: string, value: boolean) => {
        // Optimistic update
        setPrivacySettings(prev => ({ ...prev, [key]: value }))

        try {
            const token = localStorage.getItem("token")
            await fetch(`${getApiUrl()}/users/me/privacy`, {
                method: "PATCH",
                headers: {
                    "Content-Type": "application/json",
                    Authorization: `Bearer ${token}`,
                },
                body: JSON.stringify({ [key]: value }),
            })
        } catch (e) {
            // Revert on error
            setPrivacySettings(prev => ({ ...prev, [key]: !value }))
            console.error("Failed to update privacy setting:", e)
        }
    }

    if (loading) {
        return (
            <div className="flex items-center justify-center min-h-[50vh]">
                <div className="animate-pulse text-muted-foreground">Loading settings...</div>
            </div>
        )
    }

    if (!user) {
        return (
            <div className="flex flex-col items-center justify-center gap-4 py-20 min-h-[50vh]">
                <h1 className="text-2xl font-bold">Please Log In</h1>
                <p className="text-muted-foreground">You need to be logged in to access settings.</p>
                <Link href="/login">
                    <Button>Log In</Button>
                </Link>
            </div>
        )
    }

    return (
        <div className="container max-w-6xl py-8">
            {/* Header */}
            <div className="flex items-center gap-4 mb-8">
                <Link href="/profile">
                    <Button variant="ghost" size="icon">
                        <ArrowLeft className="h-4 w-4" />
                    </Button>
                </Link>
                <div>
                    <h1 className="text-3xl font-bold tracking-tight">Settings</h1>
                    <p className="text-muted-foreground">Manage your account and preferences</p>
                </div>
            </div>

            {/* Desktop: Side-by-side layout, Mobile: Tabs */}
            <div className="hidden lg:grid lg:grid-cols-[280px_1fr] lg:gap-8">
                {/* Sidebar Navigation - Sticky */}
                <nav className="space-y-1 sticky top-24 self-start">
                    <SidebarLink icon={User} label="Profile" href="#profile" active />
                    <SidebarLink icon={Palette} label="Appearance" href="#appearance" />
                    <SidebarLink icon={Eye} label="Display" href="#display" />
                    <SidebarLink icon={Bell} label="Notifications" href="#notifications" />
                    <SidebarLink icon={Shield} label="Privacy" href="#privacy" />
                </nav>

                {/* Settings Content */}
                <div className="space-y-8">
                    <ProfileSection
                        bio={bio}
                        setBio={setBio}
                        username={username}
                        setUsername={setUsername}
                        saving={profileSaving}
                        saved={profileSaved}
                        onSave={handleSaveProfile}
                    />

                    <Separator />

                    <AppearanceSection
                        avatarBgColor={avatarBgColor}
                        setAvatarBgColor={setAvatarBgColor}
                        avatarText={avatarText}
                        handleAvatarTextChange={handleAvatarTextChange}
                        username={username}
                        saving={avatarSaving}
                        saved={avatarSaved}
                        error={avatarError}
                        onSave={handleSaveAvatar}
                        userXp={(user as any)?.xp || 0}
                    />

                    <Separator />

                    <DisplaySection
                        preferences={preferences}
                        updatePreferences={updatePreferences}
                    />

                    <Separator />

                    <NotificationsSection preferences={preferences} updatePreferences={updatePreferences} />

                    <Separator />

                    <PrivacySection settings={privacySettings} onChange={handlePrivacyChange} />
                </div>
            </div>

            {/* Mobile: Tabs Layout */}
            <div className="lg:hidden">
                <Tabs defaultValue="profile" className="w-full">
                    <TabsList className="grid w-full grid-cols-5 mb-6">
                        <TabsTrigger value="profile" className="text-xs">
                            <User className="h-4 w-4" />
                        </TabsTrigger>
                        <TabsTrigger value="appearance" className="text-xs">
                            <Palette className="h-4 w-4" />
                        </TabsTrigger>
                        <TabsTrigger value="display" className="text-xs">
                            <Eye className="h-4 w-4" />
                        </TabsTrigger>
                        <TabsTrigger value="notifications" className="text-xs">
                            <Bell className="h-4 w-4" />
                        </TabsTrigger>
                        <TabsTrigger value="privacy" className="text-xs">
                            <Shield className="h-4 w-4" />
                        </TabsTrigger>
                    </TabsList>

                    <TabsContent value="profile">
                        <ProfileSection
                            bio={bio}
                            setBio={setBio}
                            username={username}
                            setUsername={setUsername}
                            saving={profileSaving}
                            saved={profileSaved}
                            onSave={handleSaveProfile}
                        />
                    </TabsContent>

                    <TabsContent value="appearance">
                        <AppearanceSection
                            avatarBgColor={avatarBgColor}
                            setAvatarBgColor={setAvatarBgColor}
                            avatarText={avatarText}
                            handleAvatarTextChange={handleAvatarTextChange}
                            username={username}
                            saving={avatarSaving}
                            saved={avatarSaved}
                            error={avatarError}
                            onSave={handleSaveAvatar}
                            userXp={(user as any)?.xp || 0}
                        />
                    </TabsContent>

                    <TabsContent value="display">
                        <DisplaySection
                            preferences={preferences}
                            updatePreferences={updatePreferences}
                        />
                    </TabsContent>

                    <TabsContent value="notifications">
                        <NotificationsSection preferences={preferences} updatePreferences={updatePreferences} />
                    </TabsContent>

                    <TabsContent value="privacy">
                        <PrivacySection settings={privacySettings} onChange={handlePrivacyChange} />
                    </TabsContent>
                </Tabs>
            </div>
        </div>
    )
}

// Sidebar Link Component
function SidebarLink({ icon: Icon, label, href, active }: {
    icon: any,
    label: string,
    href: string,
    active?: boolean
}) {
    return (
        <a
            href={href}
            className={`flex items-center gap-3 px-3 py-2 rounded-lg text-sm font-medium transition-colors ${active
                ? 'bg-primary text-primary-foreground'
                : 'text-muted-foreground hover:text-foreground hover:bg-muted'
                }`}
        >
            <Icon className="h-4 w-4" />
            {label}
        </a>
    )
}

// Profile Section
function ProfileSection({ bio, setBio, username, setUsername, saving, saved, onSave }: any) {
    return (
        <Card id="profile">
            <CardHeader>
                <CardTitle className="flex items-center gap-2">
                    <User className="h-5 w-5" />
                    Profile
                </CardTitle>
                <CardDescription>
                    Your public profile information visible to other users
                </CardDescription>
            </CardHeader>
            <CardContent className="space-y-6">
                <div className="grid gap-4 md:grid-cols-2">
                    <div className="space-y-2">
                        <Label htmlFor="username">Username</Label>
                        <Input
                            id="username"
                            placeholder="Your display name"
                            value={username}
                            onChange={(e) => setUsername(e.target.value)}
                        />
                        <p className="text-xs text-muted-foreground">
                            This will be shown on your profile and comments
                        </p>
                    </div>
                    <div className="space-y-2">
                        <Label htmlFor="email">Email</Label>
                        <Input
                            id="email"
                            disabled
                            value="(cannot be changed)"
                            className="bg-muted"
                        />
                    </div>
                </div>

                <div className="space-y-2">
                    <Label htmlFor="bio">Bio</Label>
                    <Textarea
                        id="bio"
                        placeholder="Tell other fans about yourself... When did you start following the band?"
                        value={bio}
                        onChange={(e) => setBio(e.target.value)}
                        rows={4}
                    />
                    <p className="text-xs text-muted-foreground">
                        Markdown is supported. Max 500 characters.
                    </p>
                </div>

                <div className="flex justify-end">
                    <Button onClick={onSave} disabled={saving}>
                        {saving ? "Saving..." : saved ? "Saved ✓" : "Save Changes"}
                    </Button>
                </div>
            </CardContent>
        </Card>
    )
}

// Appearance Section
function AppearanceSection({
    avatarBgColor,
    setAvatarBgColor,
    avatarText,
    handleAvatarTextChange,
    username,
    saving,
    saved,
    error,
    onSave,
    userXp = 0
}: any) {
    return (
        <Card id="appearance">
            <CardHeader>
                <CardTitle className="flex items-center gap-2">
                    <Palette className="h-5 w-5" />
                    Appearance
                </CardTitle>
                <CardDescription>
                    Customize how you appear across the site. Earn XP to unlock more colors!
                </CardDescription>
            </CardHeader>
            <CardContent className="space-y-6">
                {/* Avatar Preview */}
                <div className="flex flex-col md:flex-row gap-6 items-start md:items-center">
                    <div className="flex flex-col items-center gap-2">
                        <UserAvatar
                            bgColor={avatarBgColor}
                            text={avatarText}
                            username={username}
                            size="xl"
                        />
                        <span className="text-xs text-muted-foreground">Preview</span>
                    </div>

                    <div className="flex-1 space-y-4">
                        <div className="space-y-2">
                            <Label>Avatar Text (1-3 characters)</Label>
                            <Input
                                placeholder="e.g. ABC or 42"
                                value={avatarText}
                                onChange={(e) => handleAvatarTextChange(e.target.value)}
                                maxLength={3}
                                className="max-w-[200px] text-center text-lg font-bold uppercase"
                            />
                            <p className="text-xs text-muted-foreground">
                                Leave empty to show first letter of username
                            </p>
                        </div>
                    </div>
                </div>

                {/* Color Grid with Tiers */}
                <div className="space-y-3">
                    <div className="flex items-center justify-between">
                        <Label>Background Color</Label>
                        <span className="text-xs text-muted-foreground">Your XP: {userXp}</span>
                    </div>
                    <div className="grid grid-cols-6 gap-3">
                        {PRESET_COLORS.map((color) => {
                            const isLocked = userXp < color.xpRequired
                            return (
                                <button
                                    key={color.value}
                                    onClick={() => !isLocked && setAvatarBgColor(color.value)}
                                    disabled={isLocked}
                                    className={`relative aspect-square rounded-xl transition-all focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-ring ${isLocked
                                        ? 'opacity-40 cursor-not-allowed'
                                        : 'hover:scale-110'
                                        }`}
                                    style={{ backgroundColor: color.value }}
                                    title={isLocked
                                        ? `${color.name} - Unlock at ${color.xpRequired} XP`
                                        : `${color.name} (${color.tier})`
                                    }
                                >
                                    {avatarBgColor === color.value && !isLocked && (
                                        <Check className="absolute inset-0 m-auto h-5 w-5 text-white drop-shadow-lg" />
                                    )}
                                    {isLocked && (
                                        <Lock className="absolute inset-0 m-auto h-4 w-4 text-white/70 drop-shadow-lg" />
                                    )}
                                </button>
                            )
                        })}
                    </div>
                    <p className="text-xs text-muted-foreground">
                        Earn XP by attending shows, writing reviews, and rating performances
                    </p>
                </div>

                {error && (
                    <p className="text-sm text-destructive">{error}</p>
                )}

                <div className="flex justify-end">
                    <Button onClick={onSave} disabled={saving}>
                        {saving ? "Saving..." : saved ? "Saved" : "Save Avatar"}
                    </Button>
                </div>
            </CardContent>
        </Card>
    )
}

// Display Section
function DisplaySection({ preferences, updatePreferences }: any) {
    return (
        <Card id="display">
            <CardHeader>
                <CardTitle className="flex items-center gap-2">
                    <Eye className="h-5 w-5" />
                    Display Preferences
                </CardTitle>
                <CardDescription>
                    Control what you see while browsing
                </CardDescription>
            </CardHeader>
            <CardContent className="space-y-6">
                <SettingRow
                    label="Wiki Mode"
                    description="Hide all social features (comments, ratings, reviews) for a pure archive experience"
                    checked={preferences.wiki_mode}
                    onChange={(checked: boolean) => updatePreferences({ wiki_mode: checked })}
                />

                <Separator />

                <SettingRow
                    label="Show Ratings"
                    description="Display community ratings on shows, songs, and performances"
                    checked={preferences.show_ratings}
                    onChange={(checked: boolean) => updatePreferences({ show_ratings: checked })}
                    disabled={preferences.wiki_mode}
                />

                <Separator />

                <SettingRow
                    label="Show Comments"
                    description="Display comment sections on pages"
                    checked={preferences.show_comments}
                    onChange={(checked: boolean) => updatePreferences({ show_comments: checked })}
                    disabled={preferences.wiki_mode}
                />

                <Separator />

                <SettingRow
                    label="Show Heady Badges"
                    description="Display special badges for top-rated performances"
                    checked={true}
                    onChange={() => { }}
                    comingSoon
                />
            </CardContent>
        </Card>
    )
}

// Notifications Section
function NotificationsSection({ preferences, updatePreferences }: any) {
    return (
        <Card id="notifications">
            <CardHeader>
                <CardTitle className="flex items-center gap-2">
                    <Bell className="h-5 w-5" />
                    Notifications
                </CardTitle>
                <CardDescription>
                    Choose what email notifications you receive
                </CardDescription>
            </CardHeader>
            <CardContent className="space-y-6">
                <SettingRow
                    label="Comment Replies"
                    description="Get an email when someone replies to your review or comment"
                    checked={preferences.email_on_reply ?? true}
                    onChange={(checked: boolean) => updatePreferences({ email_on_reply: checked })}
                />

                <Separator />

                <SettingRow
                    label="Chase Song Alerts"
                    description="Get an email when a song on your chase list gets played at a show"
                    checked={preferences.email_on_chase ?? true}
                    onChange={(checked: boolean) => updatePreferences({ email_on_chase: checked })}
                />

                <Separator />

                <SettingRow
                    label="Weekly Digest"
                    description="Receive a weekly email with site highlights and new shows"
                    checked={preferences.email_digest ?? false}
                    onChange={(checked: boolean) => updatePreferences({ email_digest: checked })}
                />
            </CardContent>
        </Card>
    )
}

// Privacy Section
function PrivacySection({ settings, onChange }: {
    settings: { profile_public: boolean; show_attendance_public: boolean; appear_in_leaderboards: boolean };
    onChange: (key: string, value: boolean) => void;
}) {
    return (
        <Card id="privacy">
            <CardHeader>
                <CardTitle className="flex items-center gap-2">
                    <Shield className="h-5 w-5" />
                    Privacy
                </CardTitle>
                <CardDescription>
                    Control your privacy and data
                </CardDescription>
            </CardHeader>
            <CardContent className="space-y-6">
                <SettingRow
                    label="Public Profile"
                    description="Allow other users to view your profile, attendance history, and reviews"
                    checked={settings.profile_public}
                    onChange={(checked) => onChange("profile_public", checked)}
                />

                <Separator />

                <SettingRow
                    label="Show Attendance"
                    description="Display which shows you've attended on your public profile"
                    checked={settings.show_attendance_public}
                    onChange={(checked) => onChange("show_attendance_public", checked)}
                />

                <Separator />

                <SettingRow
                    label="Appear in Leaderboards"
                    description="Allow your name to appear on community leaderboards"
                    checked={settings.appear_in_leaderboards}
                    onChange={(checked) => onChange("appear_in_leaderboards", checked)}
                />

                <Separator />

                <div className="pt-4">
                    <h4 className="text-sm font-medium mb-2">Danger Zone</h4>
                    <div className="flex flex-col gap-2">
                        <Button
                            variant="outline"
                            size="sm"
                            className="w-fit"
                            onClick={async () => {
                                const token = localStorage.getItem("token")
                                if (!token) return
                                try {
                                    const res = await fetch(`${getApiUrl()}/users/me/export`, {
                                        headers: { Authorization: `Bearer ${token}` }
                                    })
                                    if (res.ok) {
                                        const data = await res.json()
                                        const blob = new Blob([JSON.stringify(data, null, 2)], { type: 'application/json' })
                                        const url = URL.createObjectURL(blob)
                                        const a = document.createElement('a')
                                        a.href = url
                                        a.download = 'my-fediversion-data.json'
                                        a.click()
                                        URL.revokeObjectURL(url)
                                    }
                                } catch (err) {
                                    console.error('Export failed', err)
                                }
                            }}
                        >
                            Export My Data
                        </Button>
                        <Button
                            variant="destructive"
                            size="sm"
                            className="w-fit"
                            onClick={async () => {
                                const email = prompt("To delete your account, please type your email address:")
                                if (!email) return
                                const confirm = window.confirm("Are you absolutely sure? This action cannot be undone. All your data will be permanently deleted.")
                                if (!confirm) return

                                const token = localStorage.getItem("token")
                                if (!token) return

                                try {
                                    const res = await fetch(`${getApiUrl()}/users/me`, {
                                        method: "DELETE",
                                        headers: {
                                            "Content-Type": "application/json",
                                            Authorization: `Bearer ${token}`
                                        },
                                        body: JSON.stringify({ confirm_email: email })
                                    })
                                    if (res.ok) {
                                        alert("Account deleted. Goodbye!")
                                        localStorage.removeItem("token")
                                        window.location.href = "/"
                                    } else {
                                        const data = await res.json()
                                        alert(data.detail || "Deletion failed")
                                    }
                                } catch (err) {
                                    console.error('Deletion failed', err)
                                    alert("Error deleting account")
                                }
                            }}
                        >
                            Delete Account
                        </Button>
                    </div>
                    <p className="text-xs text-muted-foreground mt-2">
                        Account deletion is permanent and cannot be undone.
                    </p>
                </div>
            </CardContent>
        </Card>
    )
}

// Reusable Setting Row
function SettingRow({
    label,
    description,
    checked,
    onChange,
    disabled,
    comingSoon
}: {
    label: string
    description: string
    checked: boolean
    onChange: (checked: boolean) => void
    disabled?: boolean
    comingSoon?: boolean
}) {
    return (
        <div className="flex items-start justify-between gap-4">
            <div className="space-y-0.5 flex-1">
                <div className="flex items-center gap-2">
                    <Label className="text-base font-medium">{label}</Label>
                    {comingSoon && (
                        <span className="text-xs bg-muted px-2 py-0.5 rounded-full text-muted-foreground">
                            Coming soon
                        </span>
                    )}
                </div>
                <p className="text-sm text-muted-foreground">
                    {description}
                </p>
            </div>
            <Switch
                checked={checked}
                onCheckedChange={onChange}
                disabled={disabled || comingSoon}
            />
        </div>
    )
}
