"use client"

import { useState } from "react"
import { Button } from "@/components/ui/button"
import { Input } from "@/components/ui/input"
import { Label } from "@/components/ui/label"
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card"
import { UserAvatar } from "@/components/ui/user-avatar"
import { getApiUrl } from "@/lib/api-config"
import { Check } from "lucide-react"

const PRESET_COLORS = [
    { value: "#3B82F6", name: "Blue" },
    { value: "#EF4444", name: "Red" },
    { value: "#10B981", name: "Green" },
    { value: "#F59E0B", name: "Amber" },
    { value: "#8B5CF6", name: "Purple" },
    { value: "#EC4899", name: "Pink" },
    { value: "#6366F1", name: "Indigo" },
    { value: "#14B8A6", name: "Teal" },
]

interface AvatarSettingsProps {
    currentBgColor?: string
    currentText?: string
    username?: string
    onSave?: (bgColor: string, text: string) => void
}

export function AvatarSettings({
    currentBgColor = "#3B82F6",
    currentText = "",
    username = "",
    onSave
}: AvatarSettingsProps) {
    const [bgColor, setBgColor] = useState(currentBgColor)
    const [text, setText] = useState(currentText)
    const [saving, setSaving] = useState(false)
    const [error, setError] = useState("")

    const handleTextChange = (value: string) => {
        // Only allow alphanumeric, max 3 chars
        const cleaned = value.replace(/[^A-Za-z0-9]/g, '').slice(0, 3).toUpperCase()
        setText(cleaned)
        setError("")
    }

    const handleSave = async () => {
        setSaving(true)
        setError("")

        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: bgColor,
                    text: text || null,
                }),
            })

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

            onSave?.(bgColor, text)
        } catch (e: any) {
            setError(e.message || "Failed to save avatar")
        } finally {
            setSaving(false)
        }
    }

    return (
        <Card>
            <CardHeader>
                <CardTitle>Customize Avatar</CardTitle>
            </CardHeader>
            <CardContent className="space-y-6">
                {/* Preview */}
                <div className="flex justify-center">
                    <UserAvatar
                        bgColor={bgColor}
                        text={text}
                        username={username}
                        size="xl"
                    />
                </div>

                {/* Color Selection */}
                <div className="space-y-2">
                    <Label>Background Color</Label>
                    <div className="grid grid-cols-4 gap-2">
                        {PRESET_COLORS.map((color) => (
                            <button
                                key={color.value}
                                onClick={() => setBgColor(color.value)}
                                className="relative h-10 rounded-lg transition-transform hover:scale-105 focus:outline-none focus:ring-2 focus:ring-offset-2"
                                style={{ backgroundColor: color.value }}
                                title={color.name}
                            >
                                {bgColor === color.value && (
                                    <Check className="absolute inset-0 m-auto h-5 w-5 text-white drop-shadow-md" />
                                )}
                            </button>
                        ))}
                    </div>
                </div>

                {/* Text Input */}
                <div className="space-y-2">
                    <Label htmlFor="avatar-text">Display Text (1-3 characters)</Label>
                    <Input
                        id="avatar-text"
                        placeholder="e.g. ABC or 123"
                        value={text}
                        onChange={(e) => handleTextChange(e.target.value)}
                        maxLength={3}
                        className="text-center text-lg font-bold uppercase"
                    />
                    <p className="text-xs text-muted-foreground">
                        Leave empty to show first letter of username
                    </p>
                </div>

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

                <Button
                    onClick={handleSave}
                    disabled={saving}
                    className="w-full"
                >
                    {saving ? "Saving..." : "Save Avatar"}
                </Button>
            </CardContent>
        </Card>
    )
}
