"use client"

import { ProfilePictureUpload } from "@/components/profile-picture-upload-v2"
import { Button } from "@/components/ui/button"
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card"
import { Input } from "@/components/ui/input"
import { Label } from "@/components/ui/label"
import { Textarea } from "@/components/ui/textarea"
import { Save, Loader2 } from "lucide-react"
import { useEffect, useState } from "react"
import { profileApi, authApi } from "@/lib/api"
import { toast } from "sonner"

export default function ProfilePage() {
    const [loading, setLoading] = useState(true)
    const [saving, setSaving] = useState(false)
    const [user, setUser] = useState<any>(null)

    const [formData, setFormData] = useState({
        fullName: "",
        email: "",
        phone: "",
        bio: "",
    })

    useEffect(() => {
        loadProfile()
    }, [])

    const loadProfile = async () => {
        try {
            const userData = await authApi.getCurrentUser()
            setUser(userData)
            setFormData({
                fullName: userData.fullName || "",
                email: userData.email || "",
                phone: userData.phone || "",
                bio: userData.bio || ""
            })
        } catch (error) {
            toast.error("Failed to load profile")
        } finally {
            setLoading(false)
        }
    }

    const handleInputChange = (field: string, value: string) => {
        setFormData(prev => ({ ...prev, [field]: value }))
    }

    const handleSubmit = async (e: React.FormEvent) => {
        e.preventDefault()
        setSaving(true)
        try {
            await profileApi.update({
                name: formData.fullName,
                phone: formData.phone,
                bio: formData.bio
            })
            toast.success("Profile updated")
        } catch (error) {
            toast.error("Failed to update profile")
        } finally {
            setSaving(false)
        }
    }

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

    return (
        <div className="max-w-2xl mx-auto py-8">
            <Card>
                <CardHeader>
                    <CardTitle className="text-2xl font-bold text-center">
                        Edit profile
                    </CardTitle>
                </CardHeader>
                <CardContent className="space-y-6">
                    <div className="flex justify-center">
                        <ProfilePictureUpload
                            fallbackText={formData.fullName ? formData.fullName.charAt(0).toUpperCase() : "U"}
                            size="xl"
                            useDatabase={false}
                            onImageChange={async (file, url) => {
                                if (file) {
                                    try {
                                        await profileApi.uploadAvatar(file)
                                        loadProfile()
                                        toast.success("Avatar updated")
                                    } catch (err) {
                                        toast.error("Failed to upload avatar")
                                    }
                                }
                            }}
                            initialImage={user?.avatarUrl}
                        />
                    </div>

                    <form onSubmit={handleSubmit} className="space-y-4">
                        <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                            <div>
                                <Label htmlFor="name">Full name</Label>
                                <Input
                                    id="name"
                                    value={formData.fullName}
                                    onChange={(e) => handleInputChange("fullName", e.target.value)}
                                />
                            </div>
                            <div>
                                <Label htmlFor="email">Email</Label>
                                <Input
                                    id="email"
                                    value={formData.email}
                                    disabled
                                    className="bg-muted"
                                />
                            </div>
                        </div>

                        <div>
                            <Label htmlFor="phone">Phone</Label>
                            <Input
                                id="phone"
                                value={formData.phone}
                                onChange={(e) => handleInputChange("phone", e.target.value)}
                            />
                        </div>

                        <div>
                            <Label htmlFor="bio">Bio</Label>
                            <Textarea
                                id="bio"
                                value={formData.bio}
                                onChange={(e) => handleInputChange("bio", e.target.value)}
                                rows={4}
                            />
                        </div>

                        <Button type="submit" className="w-full" size="lg" disabled={saving}>
                            {saving ? <Loader2 className="mr-2 h-4 w-4 animate-spin" /> : <Save className="mr-2 h-4 w-4" />}
                            Save profile
                        </Button>
                    </form>
                </CardContent>
            </Card>
        </div>
    )
}
