'use client';
import React, { useCallback, useState, useRef } from 'react';
import { useFileUpload, COMMON_VALIDATION } from '../../client/hooks/useFileUpload';
export function FileDropzone({ bucket, folder, userId, validation, generateUniquePath = true, multiple = false, accept, maxFiles = 10, disabled = false, className = '', children, onUploadComplete, onUploadStart, onUploadError, }) {
    const [isDragOver, setIsDragOver] = useState(false);
    const fileInputRef = useRef(null);
    const { uploadFiles, state, reset } = useFileUpload({
        bucket,
        folder,
        userId,
        validation,
        generateUniquePath,
    });
    const handleFileSelection = useCallback(async (files) => {
        if (disabled || state.isUploading)
            return;
        const fileArray = Array.from(files);
        // Limit number of files
        const filesToUpload = fileArray.slice(0, maxFiles);
        if (filesToUpload.length === 0)
            return;
        onUploadStart?.();
        try {
            const results = await uploadFiles(filesToUpload);
            onUploadComplete?.(results);
            // Check for any errors
            const hasError = results.some(result => result.error);
            if (hasError) {
                const errors = results
                    .filter(r => r.error)
                    .map(r => r.error)
                    .join(', ');
                onUploadError?.(errors);
            }
        }
        catch (error) {
            const errorMessage = error instanceof Error ? error.message : 'Upload failed';
            onUploadError?.(errorMessage);
        }
    }, [disabled, state.isUploading, maxFiles, onUploadStart, uploadFiles, onUploadComplete, onUploadError]);
    const handleDragOver = useCallback((e) => {
        e.preventDefault();
        if (!disabled) {
            setIsDragOver(true);
        }
    }, [disabled]);
    const handleDragLeave = useCallback((e) => {
        e.preventDefault();
        setIsDragOver(false);
    }, []);
    const handleDrop = useCallback((e) => {
        e.preventDefault();
        setIsDragOver(false);
        if (disabled)
            return;
        const files = e.dataTransfer.files;
        if (files.length > 0) {
            handleFileSelection(files);
        }
    }, [disabled, handleFileSelection]);
    const handleClick = useCallback(() => {
        if (!disabled && !state.isUploading) {
            fileInputRef.current?.click();
        }
    }, [disabled, state.isUploading]);
    const handleInputChange = useCallback((e) => {
        const files = e.target.files;
        if (files && files.length > 0) {
            handleFileSelection(files);
        }
        // Reset input value so the same file can be uploaded again
        e.target.value = '';
    }, [handleFileSelection]);
    const defaultClassName = `
    border-2 border-dashed border-gray-300 rounded-lg p-6 text-center cursor-pointer
    transition-colors duration-200 ease-in-out
    ${isDragOver ? 'border-blue-500 bg-blue-50' : 'hover:border-gray-400 hover:bg-gray-50'}
    ${disabled || state.isUploading ? 'opacity-50 cursor-not-allowed' : ''}
    ${state.error ? 'border-red-500 bg-red-50' : ''}
  `.trim();
    return (<div>
      <div className={className || defaultClassName} onDragOver={handleDragOver} onDragLeave={handleDragLeave} onDrop={handleDrop} onClick={handleClick} role="button" tabIndex={0} onKeyDown={e => {
            if (e.key === 'Enter' || e.key === ' ') {
                e.preventDefault();
                handleClick();
            }
        }}>
        <input ref={fileInputRef} type="file" multiple={multiple} accept={accept} onChange={handleInputChange} className="hidden" disabled={disabled || state.isUploading}/>

        {children || (<div className="space-y-2">
            {state.isUploading ? (<>
                <div className="text-sm text-blue-600">Uploading...</div>
                <div className="w-full bg-gray-200 rounded-full h-2">
                  <div className="bg-blue-600 h-2 rounded-full transition-all duration-300" style={{ width: `${state.progress}%` }}/>
                </div>
              </>) : (<>
                <div className="text-sm text-gray-600">
                  {isDragOver ? 'Drop files here' : `Click to upload or drag and drop ${multiple ? 'files' : 'file'}`}
                </div>
                {validation && (<div className="text-xs text-gray-500 space-y-1">
                    {validation.allowedTypes && (<div>Accepted types: {validation.allowedTypes.map(type => type.split('/')[1]).join(', ')}</div>)}
                    {validation.maxSizeBytes && (<div>Max size: {Math.round(validation.maxSizeBytes / 1024 / 1024)}MB</div>)}
                  </div>)}
              </>)}
          </div>)}
      </div>

      {state.error && <div className="mt-2 text-sm text-red-600">{state.error}</div>}

      {state.uploadedUrl && <div className="mt-2 text-sm text-green-600">Upload completed successfully!</div>}

      {state.isUploading && (<button onClick={reset} className="mt-2 px-3 py-1 text-sm text-gray-600 border border-gray-300 rounded hover:bg-gray-50">
          Cancel
        </button>)}
    </div>);
}
// Preset dropzones for common use cases
export function ImageDropzone(props) {
    return <FileDropzone {...props} validation={COMMON_VALIDATION.images} accept="image/*"/>;
}
export function DocumentDropzone(props) {
    return <FileDropzone {...props} validation={COMMON_VALIDATION.documents} accept=".pdf,.doc,.docx,.txt"/>;
}
export function VideoDropzone(props) {
    return <FileDropzone {...props} validation={COMMON_VALIDATION.videos} accept="video/*"/>;
}
export function AudioDropzone(props) {
    return <FileDropzone {...props} validation={COMMON_VALIDATION.audio} accept="audio/*"/>;
}
