"use client"
import * as React from "react"
import Cropper, { type Area } from "react-easy-crop"
import { CameraIcon, UserPlusIcon, XIcon, ZoomInIcon, ZoomOutIcon } from "lucide-react"
import { toast } from "sonner"
import { Button } from "@/components/contacts/ui/button"
import { Dialog, DialogContent, DialogDescription, DialogFooter, DialogHeader, DialogTitle } from "@/components/contacts/ui/dialog"
import { Slider } from "@/components/contacts/ui/slider"
import { cn } from "@/lib/utils"
import { ContactAvatar } from "./bits"
const MAX_BYTES = 10 * 1024 * 1024
/** The crop as a 256 × 256 WebP data URL (JPEG where WebP can't be written). */
async function cropToDataUrl(src: string, area: Area) {
const img = new Image()
img.src = src
await img.decode()
const canvas = document.createElement("canvas")
canvas.width = 256
canvas.height = 256
const ctx = canvas.getContext("2d")!
ctx.imageSmoothingQuality = "high"
ctx.drawImage(img, area.x, area.y, area.width, area.height, 0, 0, 256, 256)
const webp = canvas.toDataURL("image/webp", 0.85)
return webp.startsWith("data:image/webp") ? webp : canvas.toDataURL("image/jpeg", 0.88)
}
/**
* Click or drop a picture, crop it to a circle, keep or remove it. Without a photo: initials (or "Add" on a new,
* nameless contact) with a camera.
*/
export function AvatarUploader({ value, onChange, firstName, lastName }: { value: string; onChange: (v: string) => void; firstName: string; lastName: string }) {
const inputRef = React.useRef<HTMLInputElement>(null)
const [source, setSource] = React.useState<string | null>(null)
const [crop, setCrop] = React.useState({ x: 0, y: 0 })
const [zoom, setZoom] = React.useState(1)
const [area, setArea] = React.useState<Area | null>(null)
const [over, setOver] = React.useState(false)
const named = !!(firstName.trim() || lastName.trim())
const take = (file: File | undefined) => {
if (!file) return
if (!file.type.startsWith("image/")) return toast.error("Choose an image file (JPG, PNG, WebP…)")
if (file.size > MAX_BYTES) return toast.error("That picture is over 10 MB")
const reader = new FileReader()
reader.onload = () => {
setCrop({ x: 0, y: 0 })
setZoom(1)
setSource(String(reader.result))
}
reader.readAsDataURL(file)
}
return (
<div className="flex items-center gap-4">
<div className="relative">
<button
type="button"
aria-label={value ? "Change photo" : "Add a photo"}
onClick={() => inputRef.current?.click()}
onDragOver={(e) => {
e.preventDefault()
setOver(true)
}}
onDragLeave={() => setOver(false)}
onDrop={(e) => {
e.preventDefault()
setOver(false)
take(e.dataTransfer.files[0])
}}
className={cn(
"group/avatar relative flex size-20 items-center justify-center overflow-hidden rounded-full outline-none focus-visible:ring-3 focus-visible:ring-ring/50",
over && "ring-2 ring-foreground ring-offset-2 ring-offset-card"
)}
>
{value || named ? (
<ContactAvatar person={{ firstName, lastName, avatar: value }} size={80} />
) : (
<span className="flex size-20 flex-col items-center justify-center gap-0.5 rounded-full border border-dashed border-muted-foreground/40 bg-muted text-xs font-medium text-foreground/65">
<UserPlusIcon className="size-5" />
Add
</span>
)}
{value && (
<span className="absolute inset-0 flex flex-col items-center justify-center gap-0.5 rounded-full bg-black/55 text-[11px] font-medium text-white opacity-0 transition-opacity duration-150 group-hover/avatar:opacity-100 group-focus-visible/avatar:opacity-100 pointer-coarse:opacity-60">
<CameraIcon className="size-4" />
Edit
</span>
)}
</button>
{!value && named && (
<span aria-hidden className="pointer-events-none absolute -right-0.5 -bottom-0.5 flex size-7 items-center justify-center rounded-full border bg-background text-muted-foreground shadow-sm">
<CameraIcon className="size-3.5" />
</span>
)}
{value && (
<button
type="button"
aria-label="Remove photo"
onClick={() => onChange("")}
className="absolute -top-0.5 -right-0.5 flex size-6 items-center justify-center rounded-full border bg-background text-muted-foreground shadow-sm outline-none hover:text-foreground focus-visible:ring-2 focus-visible:ring-ring pointer-coarse:size-8"
>
<XIcon className="size-3.5" />
</button>
)}
</div>
<div className="min-w-0 text-[13px] text-muted-foreground">
<p className="font-medium text-foreground">Profile photo</p>
<p>Click or drop a picture. You can crop it next.</p>
</div>
<input
ref={inputRef}
type="file"
accept="image/*"
className="sr-only"
tabIndex={-1}
aria-hidden
onChange={(e) => {
const file = e.target.files?.[0]
e.target.value = ""
take(file)
}}
/>
<Dialog open={!!source} onOpenChange={(o) => !o && setSource(null)}>
<DialogContent className="gap-4 sm:max-w-md" showCloseButton={false}>
<DialogHeader>
<DialogTitle>Crop photo</DialogTitle>
<DialogDescription>Drag to move, scroll or use the slider to zoom.</DialogDescription>
</DialogHeader>
<div className="relative h-72 overflow-hidden rounded-lg bg-muted">
{source && (
<Cropper
image={source}
crop={crop}
zoom={zoom}
aspect={1}
cropShape="round"
showGrid={false}
onCropChange={setCrop}
onZoomChange={setZoom}
onCropComplete={(_, px) => setArea(px)}
/>
)}
</div>
<div className="flex items-center gap-3">
<ZoomOutIcon aria-hidden className="size-4 text-muted-foreground" />
<Slider aria-label="Zoom" min={1} max={3} step={0.01} value={[zoom]} onValueChange={(v) => setZoom(Array.isArray(v) ? v[0] : v)} />
<ZoomInIcon aria-hidden className="size-4 text-muted-foreground" />
</div>
<DialogFooter>
<Button variant="outline" onClick={() => setSource(null)}>
Cancel
</Button>
<Button
onClick={async () => {
if (!source || !area) return
onChange(await cropToDataUrl(source, area))
setSource(null)
}}
>
Use photo
</Button>
</DialogFooter>
</DialogContent>
</Dialog>
</div>
)
}