'use client';

import { useState, useRef } from 'react';
import { useTranslations } from 'next-intl';
import { Button, Image } from 'react-bootstrap';
import { FaCamera, FaTrash } from 'react-icons/fa';
import http from '@/http';
import { resizeImage, MAX_FILE_SIZE } from '@/utils/imageResize';

interface AvatarUploadProps {
  currentAvatarUrl: string | null;
  onAvatarChange: (url: string | null) => void;
}

const DEFAULT_AVATAR = '/images/tk-default-avatar.svg';

export default function AvatarUpload({ currentAvatarUrl, onAvatarChange }: AvatarUploadProps) {
  const t = useTranslations('ProfilePage');
  const fileInputRef = useRef<HTMLInputElement>(null);
  const [uploading, setUploading] = useState(false);
  const [error, setError] = useState('');

  const avatarSrc = currentAvatarUrl || DEFAULT_AVATAR;

  const handleFileSelect = async (e: React.ChangeEvent<HTMLInputElement>) => {
    const file = e.target.files?.[0];
    if (!file) return;

    setError('');

    if (file.size > MAX_FILE_SIZE) {
      setError(t('avatar_too_large'));
      return;
    }

    setUploading(true);
    try {
      const resized = await resizeImage(file, 300, 300);
      const formData = new FormData();
      formData.append('avatar', resized, 'avatar.jpg');

      const response = await http.post('/me/avatar', formData);

      onAvatarChange(response.data.avatarUrl);
    } catch {
      setError(t('avatar_upload_error'));
    } finally {
      setUploading(false);
      if (fileInputRef.current) fileInputRef.current.value = '';
    }
  };

  const handleDelete = async () => {
    setUploading(true);
    setError('');
    try {
      await http.delete('/me/avatar');
      onAvatarChange(null);
    } catch {
      setError(t('avatar_delete_error'));
    } finally {
      setUploading(false);
    }
  };

  return (
    <div className="text-center">
      <div className="position-relative d-inline-block mb-3">
        <Image
          src={avatarSrc}
          alt="Avatar"
          roundedCircle
          width={120}
          height={120}
          style={{ objectFit: 'cover' }}
        />
        <Button
          variant="primary"
          size="sm"
          className="position-absolute bottom-0 end-0 rounded-circle"
          onClick={() => fileInputRef.current?.click()}
          disabled={uploading}
          style={{ width: 32, height: 32, padding: 0 }}
        >
          <FaCamera size={14} />
        </Button>
      </div>

      <input
        ref={fileInputRef}
        type="file"
        accept="image/*"
        onChange={handleFileSelect}
        style={{ display: 'none' }}
      />

      {currentAvatarUrl && (
        <div>
          <Button variant="outline-danger" size="sm" onClick={handleDelete} disabled={uploading}>
            <FaTrash className="me-1" /> {t('avatar_delete')}
          </Button>
        </div>
      )}

      {error && <p className="text-danger mt-2 small">{error}</p>}
      {uploading && <p className="tk-text-muted mt-2 small">...</p>}
    </div>
  );
}
