import { useState } from 'react';
import { Upload, X, Camera } from 'lucide-react';
import { Button } from '@/components/ui/button';
import { Card, CardContent } from '@/components/ui/card';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import { Textarea } from '@/components/ui/textarea';
import { useToast } from '@/hooks/use-toast';
import { supabase } from '@/integrations/supabase/client';
import { useAuth } from '@/hooks/useAuth';

interface PhotoSubmissionUploadProps {
  onSubmissionComplete?: () => void;
  parkId?: string;
  rideId?: string;
}

export function PhotoSubmissionUpload({ onSubmissionComplete, parkId, rideId }: PhotoSubmissionUploadProps) {
  const [selectedFiles, setSelectedFiles] = useState<File[]>([]);
  const [uploading, setUploading] = useState(false);
  const [caption, setCaption] = useState('');
  const [title, setTitle] = useState('');
  const { toast } = useToast();
  const { user } = useAuth();

  const handleFileSelect = (event: React.ChangeEvent<HTMLInputElement>) => {
    const files = Array.from(event.target.files || []);
    const imageFiles = files.filter(file => file.type.startsWith('image/'));
    
    if (imageFiles.length !== files.length) {
      toast({
        title: "Invalid Files",
        description: "Only image files are allowed",
        variant: "destructive",
      });
    }
    
    setSelectedFiles(prev => [...prev, ...imageFiles].slice(0, 5)); // Max 5 files
  };

  const removeFile = (index: number) => {
    setSelectedFiles(prev => prev.filter((_, i) => i !== index));
  };

  const uploadFileToCloudflare = async (file: File): Promise<{ id: string; url: string }> => {
    // Get upload URL from Supabase edge function
    const { data: uploadData, error: uploadError } = await supabase.functions.invoke('upload-image', {
      method: 'POST',
      body: JSON.stringify({
        filename: file.name,
        contentType: file.type,
      }),
    });

    if (uploadError || !uploadData?.uploadURL) {
      throw new Error('Failed to get upload URL');
    }

    // Upload file directly to Cloudflare
    const formData = new FormData();
    formData.append('file', file);

    const uploadResponse = await fetch(uploadData.uploadURL, {
      method: 'POST',
      body: formData,
    });

    if (!uploadResponse.ok) {
      throw new Error('Failed to upload file to Cloudflare');
    }

    const result = await uploadResponse.json();
    
    // Get the delivery URL
    const { data: statusData, error: statusError } = await supabase.functions.invoke('upload-image', {
      method: 'GET',
      body: JSON.stringify({ imageId: result.result.id }),
    });

    if (statusError || !statusData?.url) {
      throw new Error('Failed to get image URL');
    }

    return {
      id: result.result.id,
      url: statusData.url,
    };
  };

  const handleSubmit = async () => {
    if (!user) {
      toast({
        title: "Authentication Required",
        description: "Please log in to submit photos",
        variant: "destructive",
      });
      return;
    }

    if (selectedFiles.length === 0) {
      toast({
        title: "No Files Selected",
        description: "Please select at least one image to submit",
        variant: "destructive",
      });
      return;
    }

    setUploading(true);
    try {
      // Upload files to Cloudflare Images first
      const photoSubmissions = await Promise.all(
        selectedFiles.map(async (file, index) => {
          const uploadResult = await uploadFileToCloudflare(file);
          
          return {
            filename: file.name,
            size: file.size,
            type: file.type,
            url: uploadResult.url,
            imageId: uploadResult.id,
            caption: index === 0 ? caption : '', // Only first image gets the caption
          };
        })
      );

      // Submit to content_submissions table
      const { error } = await supabase
        .from('content_submissions')
        .insert({
          user_id: user.id,
          submission_type: 'photo',
          content: {
            photos: photoSubmissions,
            title: title.trim() || undefined,
            caption: caption.trim() || undefined,
            park_id: parkId,
            ride_id: rideId,
            context: parkId ? 'park' : rideId ? 'ride' : 'general',
          },
          status: 'pending',
        });

      if (error) throw error;

      toast({
        title: "Photos Submitted",
        description: "Your photos have been submitted for moderation review",
      });

      // Reset form
      setSelectedFiles([]);
      setCaption('');
      setTitle('');
      onSubmissionComplete?.();

    } catch (error) {
      console.error('Error submitting photos:', error);
      toast({
        title: "Submission Failed",
        description: "Failed to submit photos. Please try again.",
        variant: "destructive",
      });
    } finally {
      setUploading(false);
    }
  };

  return (
    <Card>
      <CardContent className="p-6 space-y-4">
        <div className="flex items-center gap-2 mb-4">
          <Camera className="w-5 h-5" />
          <h3 className="text-lg font-semibold">Submit Photos</h3>
        </div>

        <div className="space-y-4">
          <div>
            <Label htmlFor="photo-title">Title (optional)</Label>
            <Input
              id="photo-title"
              placeholder="Give your photo submission a title"
              value={title}
              onChange={(e) => setTitle(e.target.value)}
              maxLength={100}
            />
          </div>

          <div>
            <Label htmlFor="photo-caption">Caption (optional)</Label>
            <Textarea
              id="photo-caption"
              placeholder="Add a caption to describe your photos"
              value={caption}
              onChange={(e) => setCaption(e.target.value)}
              rows={3}
              maxLength={500}
            />
          </div>

          <div>
            <Label htmlFor="photo-upload">Select Photos</Label>
            <div className="mt-2">
              <input
                id="photo-upload"
                type="file"
                accept="image/*"
                multiple
                onChange={handleFileSelect}
                className="hidden"
              />
              <Button
                type="button"
                variant="outline"
                onClick={() => document.getElementById('photo-upload')?.click()}
                className="w-full"
                disabled={selectedFiles.length >= 5}
              >
                <Upload className="w-4 h-4 mr-2" />
                Choose Photos {selectedFiles.length > 0 && `(${selectedFiles.length}/5)`}
              </Button>
            </div>
          </div>

          {selectedFiles.length > 0 && (
            <div className="space-y-3">
              <Label>Selected Photos:</Label>
              <div className="grid grid-cols-2 md:grid-cols-3 gap-3">
                {selectedFiles.map((file, index) => (
                  <div key={index} className="relative">
                    <img
                      src={URL.createObjectURL(file)}
                      alt={`Preview ${index + 1}`}
                      className="w-full h-24 object-cover rounded border"
                    />
                    <Button
                      type="button"
                      variant="destructive"
                      size="sm"
                      className="absolute -top-2 -right-2 h-6 w-6 rounded-full p-0"
                      onClick={() => removeFile(index)}
                    >
                      <X className="h-3 w-3" />
                    </Button>
                  </div>
                ))}
              </div>
            </div>
          )}

          <Button
            onClick={handleSubmit}
            disabled={uploading || selectedFiles.length === 0}
            className="w-full"
          >
            {uploading ? 'Submitting...' : 'Submit Photos for Review'}
          </Button>
        </div>
      </CardContent>
    </Card>
  );
}