import React, { useRef, useState } from 'react';
import { Camera, X } from 'lucide-react';
import api from '../services/api';

interface PhotoUploadProps {
    photos: string[];
    onPhotosChange: (url: string) => void;
    onRemovePhoto: (index: number) => void;
}

export const PhotoUpload: React.FC<PhotoUploadProps> = ({ photos, onPhotosChange, onRemovePhoto }) => {
    const fileInputRef = useRef<HTMLInputElement>(null);
    const [uploading, setUploading] = useState(false);

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

        // Validation: Max 500KB
        if (file.size > 500 * 1024) {
            alert('A foto deve ter no máximo 500KB.');
            if (fileInputRef.current) fileInputRef.current.value = '';
            return;
        }

        // Validation: JPG only
        if (file.type !== 'image/jpeg' && file.type !== 'image/jpg') {
            alert('Apenas fotos no formato JPG são permitidas.');
            if (fileInputRef.current) fileInputRef.current.value = '';
            return;
        }

        setUploading(true);
        const formData = new FormData();
        formData.append('photo', file);

        try {
            const response = await api.post('/inspections/upload', formData, {
                headers: {
                    'Content-Type': 'multipart/form-data',
                },
            });
            onPhotosChange(response.data.url);
        } catch (error) {
            console.error('Error uploading photo:', error);
            alert('Erro ao enviar foto. Verifique se o tamanho é menor que 500KB.');
        } finally {
            setUploading(false);
            if (fileInputRef.current) {
                fileInputRef.current.value = '';
            }
        }
    };

    return (
        <div className="space-y-3">
            <span className="text-[10px] font-bold text-primary uppercase tracking-[0.15em] ml-1">Fotos da Inspeção</span>

            <div className="grid grid-cols-2 md:grid-cols-4 gap-4">
                {photos.map((photo, index) => (
                    <div key={index} className="relative group aspect-square rounded-xl overflow-hidden border border-border/40 bg-surface-soft">
                        <img
                            src={photo}
                            alt={`Evidência ${index + 1}`}
                            className="w-full h-full object-cover transition-transform group-hover:scale-105"
                        />
                        <div className="absolute inset-0 bg-black/40 opacity-0 group-hover:opacity-100 transition-opacity flex items-center justify-center">
                            <button
                                type="button"
                                onClick={() => onRemovePhoto(index)}
                                className="p-2 bg-error text-white rounded-full hover:bg-error/90 transition-colors"
                                aria-label={`Remover foto ${index + 1}`}
                                title={`Remover foto ${index + 1}`}
                            >
                                <X size={16} />
                            </button>
                        </div>
                    </div>
                ))}

                <button
                    type="button"
                    onClick={() => fileInputRef.current?.click()}
                    disabled={uploading}
                    className="aspect-square flex flex-col items-center justify-center gap-1 rounded-xl border-2 border-dashed border-border/60 hover:border-primary/50 bg-surface hover:bg-surface-hover transition-all text-text-muted hover:text-primary disabled:opacity-50 disabled:cursor-not-allowed"
                    aria-label="Adicionar foto"
                    title="Adicionar foto (JPG, Max 500KB)"
                >
                    {uploading ? (
                        <div className="animate-spin rounded-full h-6 w-6 border-b-2 border-primary"></div>
                    ) : (
                        <>
                            <Camera size={24} className="mb-1" />
                            <span className="text-xs font-bold uppercase">Adicionar</span>
                            <span className="text-[9px] font-medium opacity-70">Máx 500kb (JPG)</span>
                        </>
                    )}
                </button>
            </div>

            <input
                type="file"
                ref={fileInputRef}
                className="hidden"
                accept="image/jpeg, image/jpg"
                onChange={handleFileChange}
                aria-label="Selecionar arquivo de foto"
                title="Selecionar arquivo de foto"
            />
        </div>
    );
};
