import { useState } from 'react';
import { Upload } from 'lucide-react';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { useToast } from '@/hooks/use-toast';
import { getErrorMessage } from '@/lib/errorHandler';

interface SimplePhotoUploadProps {
  onUpload: (imageId: string, imageUrl: string) => Promise<void>;
  disabled?: boolean;
  children?: React.ReactNode;
}

export function SimplePhotoUpload({ onUpload, disabled, children }: SimplePhotoUploadProps) {
  const [uploading, setUploading] = useState(false);
  const { toast } = useToast();

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

    if (!file.type.startsWith('image/')) {
      toast({
        title: 'Invalid file',
        description: 'Please select an image file',
        variant: 'destructive'
      });
      return;
    }

    if (file.size > 5 * 1024 * 1024) {
      toast({
        title: 'File too large',
        description: 'Please select an image under 5MB',
        variant: 'destructive'
      });
      return;
    }

    setUploading(true);
    try {
      // Create a mock upload for now - in real implementation would upload to CloudFlare
      const mockImageId = `avatar_${Date.now()}`;
      const mockImageUrl = URL.createObjectURL(file);
      
      await onUpload(mockImageId, mockImageUrl);
      
      toast({
        title: 'Image uploaded',
        description: 'Your image has been uploaded successfully'
      });
    } catch (error: unknown) {
      toast({
        title: 'Upload failed',
        description: getErrorMessage(error),
        variant: 'destructive'
      });
    } finally {
      setUploading(false);
      // Reset input
      event.target.value = '';
    }
  };

  return (
    <div className="relative">
      <Input
        type="file"
        accept="image/*"
        onChange={handleFileSelect}
        className="absolute inset-0 w-full h-full opacity-0 cursor-pointer"
        disabled={disabled || uploading}
      />
      {children || (
        <Button variant="outline" disabled={disabled || uploading}>
          <Upload className="w-4 h-4 mr-2" />
          {uploading ? 'Uploading...' : 'Upload Image'}
        </Button>
      )}
    </div>
  );
}