'use client';

import { useRef, useState } from 'react';
import { Camera } from 'lucide-react';
import { getAuthHeaders } from '@/lib/auth';

const API_URL = process.env.NEXT_PUBLIC_API_URL || 'http://localhost:3000/v1';

interface AvatarUploadProps {
  userId: string;
  currentUrl: string | null;
  initials: string;
  disabled?: boolean;
  onUploaded: (url: string) => void;
}

export function AvatarUpload({ userId, currentUrl, initials, disabled, onUploaded }: AvatarUploadProps) {
  const inputRef = useRef<HTMLInputElement>(null);
  const [uploading, setUploading] = useState(false);
  const [preview, setPreview] = useState<string | null>(null);

  const avatarSrc = preview ?? (currentUrl ? `${API_URL.replace('/v1', '')}${currentUrl}` : null);

  const handleFile = async (file: File) => {
    if (file.size > 5 * 1024 * 1024) {
      alert('Максимальный размер файла — 5 МБ');
      return;
    }
    if (!['image/jpeg', 'image/png', 'image/webp'].includes(file.type)) {
      alert('Допустимые форматы: JPEG, PNG, WebP');
      return;
    }

    setPreview(URL.createObjectURL(file));
    setUploading(true);

    try {
      const form = new FormData();
      form.append('avatar', file);
      const res = await fetch(`${API_URL}/users/${userId}/avatar`, {
        method: 'POST',
        headers: getAuthHeaders(),
        body: form,
      });
      if (!res.ok) throw new Error('Ошибка загрузки');
      const data = (await res.json()) as { avatarUrl: string };
      onUploaded(data.avatarUrl);
    } catch {
      setPreview(null);
      alert('Не удалось загрузить фото');
    } finally {
      setUploading(false);
    }
  };

  return (
    <div className="relative group">
      <div className="h-28 w-28 rounded-full overflow-hidden bg-primary/10 flex items-center justify-center mx-auto">
        {avatarSrc ? (
          <img src={avatarSrc} alt="Аватар" className="h-full w-full object-cover" />
        ) : (
          <span className="text-3xl font-bold text-primary">{initials}</span>
        )}
      </div>

      {!disabled && (
        <>
          <button
            type="button"
            onClick={() => inputRef.current?.click()}
            disabled={uploading}
            className="absolute inset-0 mx-auto h-28 w-28 rounded-full flex items-center justify-center bg-black/0 group-hover:bg-black/40 transition-colors cursor-pointer"
          >
            <Camera className="h-6 w-6 text-white opacity-0 group-hover:opacity-100 transition-opacity" />
          </button>
          <input
            ref={inputRef}
            type="file"
            accept="image/jpeg,image/png,image/webp"
            className="hidden"
            onChange={(e) => {
              const file = e.target.files?.[0];
              if (file) handleFile(file);
              e.target.value = '';
            }}
          />
        </>
      )}

      {uploading && (
        <div className="absolute inset-0 mx-auto h-28 w-28 rounded-full flex items-center justify-center bg-black/50">
          <div className="animate-spin h-6 w-6 border-2 border-white border-t-transparent rounded-full" />
        </div>
      )}
    </div>
  );
}
