'use client';
import {useRef, useState, type ChangeEvent} from 'react';
import {Pencil, LoaderCircle, UserRound} from 'lucide-react';
import {Avatar, AvatarImage, AvatarFallback} from './ui/avatar';
import {MAX_PHOTO_BYTES, photoTypes, profileInitial, profilePhotoUrl} from '@/lib/profile-photo';
import type {Locale} from '@/lib/catalog';

type AvatarProps = {name: string; userId: string; path?: string | null; className?: string};
export function UserAvatar({name, userId, path, className = ''}: AvatarProps) {
  const initial = profileInitial(name);
  return <Avatar className={`user-avatar ${className}`} aria-label={name}>
    {path && <AvatarImage key={path} src={profilePhotoUrl(userId, path)} alt={name}/>}
    <AvatarFallback>{initial || <UserRound size={20}/>}</AvatarFallback>
  </Avatar>;
}

const words = {
  fa: {edit:'ویرایش عکس پروفایل', help:'JPG، PNG یا WebP • حداکثر ۲ مگابایت', saving:'در حال ذخیره عکس…', saved:'عکس پروفایل ذخیره شد.', invalid:'عکس JPG، PNG یا WebP با حجم حداکثر ۲ مگابایت انتخاب کنید.', error:'ذخیره عکس انجام نشد. دوباره تلاش کنید.'},
  en: {edit:'Edit profile photo', help:'JPG, PNG or WebP • Up to 2 MB', saving:'Saving photo…', saved:'Profile photo saved.', invalid:'Choose a JPG, PNG or WebP photo up to 2 MB.', error:'Could not save photo. Please try again.'},
  ar: {edit:'تعديل صورة الملف الشخصي', help:'JPG أو PNG أو WebP • حتى ٢ ميغابايت', saving:'جارٍ حفظ الصورة…', saved:'تم حفظ صورة الملف الشخصي.', invalid:'اختر صورة JPG أو PNG أو WebP بحجم أقصى ٢ ميغابايت.', error:'تعذر حفظ الصورة. حاول مجدداً.'},
};
export function ProfilePhotoEditor(props: AvatarProps & {locale: Locale; onChanged: () => Promise<void>}) {
  const input = useRef<HTMLInputElement>(null), [busy, setBusy] = useState(false), [error, setError] = useState(''), [saved, setSaved] = useState(false);
  const [latestPath, setLatestPath] = useState<string | null>(null);
  const copy = words[props.locale];
  async function upload(event: ChangeEvent<HTMLInputElement>) {
    const file = event.target.files?.[0]; event.target.value = '';
    if (!file || busy) return;
    setError(''); setSaved(false);
    if (!photoTypes.some(type => type === file.type) || file.size > MAX_PHOTO_BYTES) {setError(copy.invalid); return;}
    setBusy(true);
    try {
      const response = await fetch('/api/avatar', {method: 'POST', headers: {'Content-Type': file.type}, body: file});
      const data = await response.json() as {ok?: boolean; path?: string; error?: string};
      if (!response.ok || !data.ok || !data.path) throw new Error(data.error || copy.error);
      setLatestPath(data.path); setSaved(true); await props.onChanged();
    } catch (err) {setError(err instanceof Error ? err.message : copy.error);}
    finally {setBusy(false);}
  }
  return <span className="profile-photo-editor" aria-busy={busy}>
    <span className="profile-photo-control"><UserAvatar {...props} path={latestPath || props.path} className="dash-profile-avatar"/>
      <button type="button" className="profile-photo-edit" disabled={busy} onClick={() => input.current?.click()} aria-label={copy.edit} title={copy.edit}>{busy ? <LoaderCircle size={16} className="account-spinner"/> : <Pencil size={16}/>}</button>
      <input ref={input} type="file" accept="image/jpeg,image/png,image/webp" onChange={event => void upload(event)} hidden aria-label={copy.edit} disabled={busy}/>
    </span>
    <span className="profile-photo-feedback" role={error ? 'alert' : 'status'} data-error={!!error}>{error || (busy ? copy.saving : saved ? copy.saved : copy.help)}</span>
  </span>;
}
