'use client';

import { useState, useCallback } from 'react';
import { Plus, Loader2 } from 'lucide-react';
import { Button } from '@/components/ui/button';
import { Card } from '@/components/ui/card';
import { toast } from 'sonner';

interface ImageUploadProps {
  type: 'header' | 'footer';
  onUploadSuccess: (fileInfo?: { filename: string; path: string }) => void;
}

export function ImageUpload({ type, onUploadSuccess }: ImageUploadProps) {
  const [uploading, setUploading] = useState(false);
  const [isDragOver, setIsDragOver] = useState(false);

  const handleDragOver = useCallback((e: React.DragEvent) => {
    e.preventDefault();
    setIsDragOver(true);
  }, []);

  const handleDragLeave = useCallback((e: React.DragEvent) => {
    e.preventDefault();
    setIsDragOver(false);
  }, []);

  const handleDrop = useCallback((e: React.DragEvent) => {
    e.preventDefault();
    setIsDragOver(false);

    const files = Array.from(e.dataTransfer.files);
    const imageFile = files.find((file) => file.type.startsWith('image/'));

    if (imageFile) {
      uploadImage(imageFile);
    } else {
      toast.error('Please drop an image file');
    }
  }, []);

  const handleFileSelect = useCallback((e: React.ChangeEvent<HTMLInputElement>) => {
    const file = e.target.files?.[0];
    if (file) {
      uploadImage(file);
    }
    // Reset the input to allow selecting the same file again
    e.target.value = '';
  }, []);

  const uploadImage = async (file: File) => {
    setUploading(true);

    try {
      const formData = new FormData();
      formData.append('file', file);

      const response = await fetch(`/api/upload/${type}`, {
        method: 'POST',
        body: formData,
      });

      const result = await response.json();

      if (response.ok) {
        toast.success(`${type.charAt(0).toUpperCase() + type.slice(1)} uploaded successfully!`);
        onUploadSuccess(result);
      } else {
        toast.error(result.error || 'Upload failed');
      }
    } catch (error) {
      console.error('Upload error:', error);
      toast.error('Upload failed. Please try again.');
    } finally {
      setUploading(false);
    }
  };

  return (
    <Card
      className={`p-4 border-2 border-dashed transition-all duration-200 cursor-pointer ${isDragOver
        ? 'border-blue-400 bg-blue-50'
        : 'border-gray-300 hover:border-blue-300 hover:bg-gray-50'
        } ${uploading ? 'opacity-50 pointer-events-none' : ''}`}
      onDragOver={handleDragOver}
      onDragLeave={handleDragLeave}
      onDrop={handleDrop}
    >
      <label
        htmlFor={`${type}-upload`}
        className="cursor-pointer w-full flex flex-col items-center justify-center gap-2 text-center"
      >
        {uploading ? (
          <Loader2 className="h-6 w-6 text-blue-500 animate-spin" />
        ) : (
          <Plus className={`h-6 w-6 ${isDragOver ? 'text-blue-500' : 'text-gray-400'}`} />
        )}
        <div>
          <p className="text-sm font-medium text-gray-700">
            {uploading ? 'Uploading...' : `Add ${type}`}
          </p>
          <p className="text-xs text-gray-500">
            {uploading ? 'Please wait' : 'Drop image or click to browse'}
          </p>
        </div>
      </label>
      <input
        id={`${type}-upload`}
        type="file"
        accept="image/jpeg,image/jpg,image/png,image/gif,image/svg+xml"
        onChange={handleFileSelect}
        className="hidden"
        disabled={uploading}
      />
    </Card>
  );
}