'use client';

import { useCallback, useState, useRef } from 'react';
import { Upload, Loader2, Check } from 'lucide-react';

export interface MediaUploaderProps {
  /** Called when upload completes successfully */
  onUploadComplete?: (result: { url: string; path: string }) => void;
  /** Called on error */
  onError?: (error: string) => void;
  /** Upload function from useMediaUpload hook */
  upload: (file: File) => Promise<{ url: string; path: string }>;
  /** Whether an upload is currently in progress */
  isUploading?: boolean;
  /** Upload progress percentage (0-100) */
  progress?: number;
  /** Accepted file types (e.g., "image/*,video/*") */
  accept?: string;
  /** Max file size in MB */
  maxSizeMB?: number;
}

export function MediaUploader({
  onUploadComplete,
  onError,
  upload,
  isUploading = false,
  progress = 0,
  accept = 'image/*,video/*',
  maxSizeMB = 50,
}: MediaUploaderProps) {
  const [isDragOver, setIsDragOver] = useState(false);
  const [lastResult, setLastResult] = useState<{ url: string; path: string } | null>(null);
  const fileInputRef = useRef<HTMLInputElement>(null);

  const handleFile = useCallback(async (file: File) => {
    // Validate file type (accept prop only restricts file picker, not drag-and-drop)
    if (accept) {
      const acceptedTypes = accept.split(',').map((t) => t.trim());
      const isAccepted = acceptedTypes.some((type) => {
        if (type.endsWith('/*')) return file.type.startsWith(type.replace('/*', '/'));
        return file.type === type;
      });
      if (!isAccepted) {
        onError?.(`File type "${file.type}" is not accepted. Allowed: ${accept}`);
        return;
      }
    }

    if (file.size > maxSizeMB * 1024 * 1024) {
      onError?.(`File too large. Maximum size is ${maxSizeMB}MB.`);
      return;
    }

    try {
      const result = await upload(file);
      setLastResult(result);
      onUploadComplete?.(result);
    } catch (err) {
      onError?.(err instanceof Error ? err.message : 'Upload failed');
    }
  }, [upload, accept, maxSizeMB, onUploadComplete, onError]);

  const handleDrop = useCallback((e: React.DragEvent) => {
    e.preventDefault();
    setIsDragOver(false);
    const file = e.dataTransfer.files[0];
    if (file) handleFile(file);
  }, [handleFile]);

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

  const handleDragLeave = useCallback(() => {
    setIsDragOver(false);
  }, []);

  const handleClick = () => fileInputRef.current?.click();

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

  return (
    <div
      onDrop={handleDrop}
      onDragOver={handleDragOver}
      onDragLeave={handleDragLeave}
      onClick={isUploading ? undefined : handleClick}
      className={`
        relative border-2 border-dashed rounded-lg p-8 text-center transition-colors
        ${isDragOver
          ? 'border-[var(--accent)] bg-[var(--accent)]/5'
          : 'border-[var(--border-muted)] hover:border-[var(--border-default)]'}
        ${isUploading ? 'pointer-events-none opacity-75' : 'cursor-pointer'}
      `}
    >
      <input
        ref={fileInputRef}
        type="file"
        accept={accept}
        onChange={handleInputChange}
        className="hidden"
      />

      {isUploading ? (
        <div className="space-y-3">
          <Loader2 className="h-8 w-8 animate-spin text-[var(--accent)] mx-auto" />
          <p className="text-sm text-[var(--text-muted)]">Uploading... {progress}%</p>
          <div className="w-full max-w-xs mx-auto h-2 rounded-full bg-[var(--surface-200)] overflow-hidden">
            <div
              className="h-full rounded-full bg-[var(--accent)] transition-all duration-300"
              style={{ width: `${progress}%` }}
            />
          </div>
        </div>
      ) : lastResult ? (
        <div className="space-y-2">
          <Check className="h-8 w-8 text-green-500 mx-auto" />
          <p className="text-sm text-[var(--text-primary)]">Upload complete</p>
          <button
            onClick={(e) => { e.stopPropagation(); setLastResult(null); }}
            className="text-xs text-[var(--text-muted)] hover:text-[var(--text-primary)] underline"
          >
            Upload another
          </button>
        </div>
      ) : (
        <div className="space-y-2">
          <Upload className="h-8 w-8 text-[var(--text-muted)] mx-auto" />
          <p className="text-sm text-[var(--text-primary)]">
            Drop a file here or click to browse
          </p>
          <p className="text-xs text-[var(--text-muted)]">
            Max {maxSizeMB}MB
          </p>
        </div>
      )}
    </div>
  );
}
