'use client';

import { useCallback, useRef, useMemo } from 'react';
import { useUploady } from '@rpldy/uploady';
import { Plus } from 'lucide-react';
import { Button } from '@djangocfg/ui-core/components';
import { cn } from '@djangocfg/ui-core/lib';
import { buildAcceptString, logger } from '../utils';
import type { AssetType } from '../types';

interface UploadAddButtonProps {
  accept?: AssetType[];
  multiple?: boolean;
  maxSizeMB?: number;
  disabled?: boolean;
  className?: string;
  variant?: 'default' | 'outline' | 'ghost' | 'secondary';
  size?: 'default' | 'sm' | 'lg' | 'icon';
  children?: React.ReactNode;
}

export function UploadAddButton({
  accept = ['image', 'audio', 'video', 'document'],
  multiple = true,
  maxSizeMB = 100,
  disabled = false,
  className,
  variant = 'outline',
  size = 'default',
  children,
}: UploadAddButtonProps) {
  const { upload } = useUploady();
  const inputRef = useRef<HTMLInputElement>(null);

  const acceptString = useMemo(() => buildAcceptString(accept), [accept]);

  const handleFiles = useCallback((files: FileList | File[]) => {
    const fileArray = Array.from(files);
    const maxBytes = maxSizeMB * 1024 * 1024;

    const validFiles = fileArray.filter(file => {
      if (file.size > maxBytes) {
        logger.warn(`File ${file.name} exceeds max size of ${maxSizeMB}MB`);
        return false;
      }
      return true;
    });

    if (validFiles.length > 0) {
      upload(validFiles);
    }
  }, [upload, maxSizeMB]);

  const handleClick = useCallback(() => {
    inputRef.current?.click();
  }, []);

  const handleInputChange = useCallback((e: React.ChangeEvent<HTMLInputElement>) => {
    if (e.target.files?.length) {
      handleFiles(e.target.files);
    }
    e.target.value = '';
  }, [handleFiles]);

  return (
    <>
      <input
        ref={inputRef}
        type="file"
        accept={acceptString}
        multiple={multiple}
        onChange={handleInputChange}
        className="hidden"
        disabled={disabled}
      />
      <Button
        variant={variant}
        size={size}
        disabled={disabled}
        onClick={handleClick}
        className={cn(className)}
      >
        {children || (
          <>
            <Plus className="h-4 w-4 mr-2" />
            Add Files
          </>
        )}
      </Button>
    </>
  );
}
