"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
} from "lucide-react"
import Link from "next/link"

// Avatar color palette - Jewel Tones (Primary Set)
const PRESET_COLORS = [
    { value: "#0F4C81", name: "Sapphire" },
    { value: "#9B111E", name: "Ruby" },
    { value: "#50C878", name: "Emerald" },
    { value: "#9966CC", name: "Amethyst" },
    { value: "#0D98BA", name: "Topaz" },
    { value: "#E0115F", name: "Rose Quartz" },
    { value: "#082567", name: "Lapis" },
    { value: "#FF7518", name: "Carnelian" },
    { value: "#006B3C", name: "Jade" },
    { value: "#1C1C1C", name: "Onyx" },
    { value: "#E6E200", name: "Citrine" },
    { value: "#702963", name: "Garnet" },
]

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("#1E3A8A")
    const [avatarText, setAvatarText] = useState("")
    const [avatarSaving, setAvatarSaving] = useState(false)
    const [avatarSaved, setAvatarSaved] = useState(false)
    const [avatarError, setAvatarError] = useState("")

    useEffect(() => {
        if (user) {
            const extUser = user as any
            setBio(extUser.bio || "")
            setUsername(extUser.email?.split('@')[0] || "")
            setAvatarBgColor(extUser.avatar_bg_color || "#1E3A8A")
            setAvatarText(extUser.avatar_text || "")
        }
    }, [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)
        }
    }

    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 */}
                <nav className="space-y-1">
                    <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}
                    />

                    <Separator />

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

                    <Separator />

                    <NotificationsSection />

                    <Separator />

                    <PrivacySection />
                </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}
                        />
                    </TabsContent>

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

                    <TabsContent value="notifications">
                        <NotificationsSection />
                    </TabsContent>

                    <TabsContent value="privacy">
                        <PrivacySection />
                    </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
}: 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
                </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 */}
                <div className="space-y-3">
                    <Label>Background Color</Label>
                    <div className="grid grid-cols-6 gap-3">
                        {PRESET_COLORS.map((color) => (
                            <button
                                key={color.value}
                                onClick={() => setAvatarBgColor(color.value)}
                                className="relative aspect-square rounded-xl transition-all hover:scale-110 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-ring"
                                style={{ backgroundColor: color.value }}
                                title={color.name}
                            >
                                {avatarBgColor === color.value && (
                                    <Check className="absolute inset-0 m-auto h-5 w-5 text-white drop-shadow-lg" />
                                )}
                            </button>
                        ))}
                    </div>
                </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() {
    return (
        <Card id="notifications">
            <CardHeader>
                <CardTitle className="flex items-center gap-2">
                    <Bell className="h-5 w-5" />
                    Notifications
                </CardTitle>
                <CardDescription>
                    Choose what updates you receive
                </CardDescription>
            </CardHeader>
            <CardContent className="space-y-6">
                <SettingRow
                    label="Comment Replies"
                    description="Get notified when someone replies to your comment"
                    checked={true}
                    onChange={() => { }}
                    comingSoon
                />

                <Separator />

                <SettingRow
                    label="New Show Added"
                    description="Get notified when a new show is added to the archive"
                    checked={true}
                    onChange={() => { }}
                    comingSoon
                />

                <Separator />

                <SettingRow
                    label="Chase Song Played"
                    description="Get notified when a song on your chase list gets played"
                    checked={true}
                    onChange={() => { }}
                    comingSoon
                />

                <Separator />

                <SettingRow
                    label="Weekly Digest"
                    description="Receive a weekly email with site highlights"
                    checked={false}
                    onChange={() => { }}
                    comingSoon
                />
            </CardContent>
        </Card>
    )
}

// Privacy Section
function PrivacySection() {
    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={true}
                    onChange={() => { }}
                    comingSoon
                />

                <Separator />

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

                <Separator />

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

                <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" disabled>
                            Export My Data
                        </Button>
                        <Button variant="destructive" size="sm" className="w-fit" disabled>
                            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>
    )
}
