"use client"

import { toast } from "sonner"
import { ContactAvatarPicker } from "@/components/gmail/contacts/contact-avatar-picker"
import { CompteSettingsCard } from "@/components/compte/compte-settings-card"
import {
  useDeleteUserAvatar,
  useUpdateUserAvatar,
} from "@/lib/api/hooks/use-user-avatar-mutations"

export function CompteAvatarField({
  avatarUrl,
  name,
  email,
}: {
  avatarUrl?: string
  name: string
  email: string
}) {
  const updateAvatar = useUpdateUserAvatar()
  const deleteAvatar = useDeleteUserAvatar()
  const pending = updateAvatar.isPending || deleteAvatar.isPending

  async function handleChange(next: string | undefined) {
    try {
      if (next) {
        await updateAvatar.mutateAsync(next)
        toast.success("Photo de profil mise à jour.")
      } else {
        await deleteAvatar.mutateAsync()
        toast.success("Photo de profil supprimée.")
      }
    } catch (err) {
      toast.error(
        err instanceof Error ? err.message : "Impossible de mettre à jour la photo."
      )
    }
  }

  return (
    <CompteSettingsCard className="flex flex-col items-center gap-3 sm:flex-row sm:items-center sm:gap-6">
      <ContactAvatarPicker
        avatarUrl={avatarUrl}
        displayName={name}
        email={email}
        variant="page"
        className={pending ? "pointer-events-none opacity-60" : undefined}
        onChange={(next) => void handleChange(next)}
      />
      <div className="min-w-0 text-center sm:text-left">
        <h3 className="text-sm font-medium text-foreground">Photo de profil</h3>
        <p className="mt-1 text-sm text-muted-foreground">
          Visible dans l&apos;en-tête de la suite et sur votre page compte. JPEG, PNG, GIF
          ou WebP — 512 Ko max.
        </p>
      </div>
    </CompteSettingsCard>
  )
}
