import { useState, useEffect } from 'react';
import { Card, CardContent } from "@/components/ui/card";
import { Button } from "@/components/ui/button";
import { Upload, X, AlertCircle } from 'lucide-react';
import { Alert, AlertDescription } from "@/components/ui/alert";

interface BannerUploadProps {
  onImageChange?: (file: File | null) => void;
  defaultImage?: string;
  maxSizeMB?: number;
}

export default function BannerImageUpload({ 
  onImageChange, 
  defaultImage,
  maxSizeMB = 5 
}: BannerUploadProps) {
  const [previewUrl, setPreviewUrl] = useState<string | null>(defaultImage || null);
  const [error, setError] = useState<string | null>(null);
  const [isDragging, setIsDragging] = useState(false);

  const acceptedTypes = ['image/jpeg', 'image/png', 'image/webp'];
  const maxSize = maxSizeMB * 1024 * 1024; // Convert MB to bytes

  const validateFile = (file: File): string | null => {
    if (!acceptedTypes.includes(file.type)) {
      return 'Please upload a valid image file (JPG, PNG, or WebP)';
    }
    if (file.size > maxSize) {
      return `File size should be less than ${maxSizeMB}MB`;
    }
    return null;
  };

  const handleFile = (file: File) => {
    const validationError = validateFile(file);
    if (validationError) {
      setError(validationError);
      return;
    }

    // Clear any existing error
    setError(null);

    // Create preview URL
    const objectUrl = URL.createObjectURL(file);
    setPreviewUrl(objectUrl);

    // Notify parent component
    if (onImageChange) {
      onImageChange(file);
    }
  };

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

  const handleDrop = (e: React.DragEvent<HTMLDivElement>) => {
    e.preventDefault();
    setIsDragging(false);

    const file = e.dataTransfer.files?.[0];
    if (file) {
      handleFile(file);
    }
  };

  const handleDragOver = (e: React.DragEvent<HTMLDivElement>) => {
    e.preventDefault();
    setIsDragging(true);
  };

  const handleDragLeave = (e: React.DragEvent<HTMLDivElement>) => {
    e.preventDefault();
    setIsDragging(false);
  };

  const removeBanner = () => {
    if (previewUrl) {
      URL.revokeObjectURL(previewUrl);
    }
    setPreviewUrl(null);
    setError(null);
    if (onImageChange) {
      onImageChange(null);
    }
  };

  // Cleanup preview URL when component unmounts
  useEffect(() => {
    return () => {
      if (previewUrl && previewUrl !== defaultImage) {
        URL.revokeObjectURL(previewUrl);
      }
    };
  }, [previewUrl, defaultImage]);

  return (
    <div className="space-y-4 col-span-2">
      <label>Upload Course Banner</label>
      <div
        className={`relative w-full h-64 rounded-lg overflow-hidden border-2 border-dashed transition-colors
          ${isDragging ? 'border-purple-500 bg-purple-50' : 'border-gray-300 bg-gray-50'}
          ${error ? 'border-red-300' : ''}`}
        onDrop={handleDrop}
        onDragOver={handleDragOver}
        onDragLeave={handleDragLeave}
      >
        {previewUrl ? (
          <>
            <img
              src={previewUrl}
              alt="Banner preview"
              className="w-full h-full object-cover"
            />
            <div className="absolute inset-0 bg-black bg-opacity-40 opacity-0 hover:opacity-100 transition-opacity">
              <div className="absolute inset-0 flex items-center justify-center space-x-4">
                <Button
                  type="button"
                  variant="outline"
                  className="bg-white hover:bg-gray-100"
                  onClick={() => document.getElementById('banner-upload')?.click()}
                >
                  <Upload className="h-5 w-5 mr-2" />
                  Change Banner
                </Button>
                <Button
                  type="button"
                  variant="destructive"
                  onClick={removeBanner}
                >
                  <X className="h-5 w-5 mr-2" />
                  Remove Banner
                </Button>
              </div>
            </div>
          </>
        ) : (
          <div className="absolute inset-0 flex flex-col items-center justify-center">
            <Upload className="h-12 w-12 text-gray-400 mb-4" />
            <div className="text-center">
              <Button
                type="button"
                variant="outline"
                className="mb-2"
                onClick={() => document.getElementById('banner-upload')?.click()}
              >
                Choose File
              </Button>
              <p className="text-sm text-gray-500">or drag and drop your image here</p>
              <p className="text-xs text-gray-400 mt-2">
                Supports: JPG, PNG, WebP (max {maxSizeMB}MB)
              </p>
            </div>
          </div>
        )}

        <input
          id="banner-upload"
          type="file"
          className="hidden"
          accept={acceptedTypes.join(',')}
          onChange={handleFileSelect}
        />
      </div>

      {error && (
        <Alert variant="destructive">
          <AlertCircle className="h-4 w-4" />
          <AlertDescription>{error}</AlertDescription>
        </Alert>
      )}
    </div>
  );
}