import React, { useState } from 'react';
import BaseButton from '../BaseButton';
import CardBox from '../CardBox';
import UploadProgressList, { UploadQueueItem } from './UploadProgressList';

export type Asset = {
  id: string;
  name: string;
  asset_type: 'image' | 'video' | 'audio' | 'file';
  type?:
    | 'icon'
    | 'background_image'
    | 'audio'
    | 'video'
    | 'transition'
    | 'logo'
    | 'favicon'
    | 'document'
    | 'general';
  cdn_url?: string | null;
  mime_type?: string | null;
};

export type AssetSection = {
  key:
    | 'images'
    | 'backgroundImages'
    | 'audio'
    | 'video'
    | 'transitions'
    | 'logo';
  label: string;
  accept: string;
  assetFormat: 'image' | 'video' | 'audio';
  assetCategory: NonNullable<Asset['type']>;
  legacyTag: string;
};

type AssetSectionCardProps = {
  section: AssetSection;
  assets: Asset[];
  uploadQueue: UploadQueueItem[];
  isUploading: boolean;
  isLoadingAssets: boolean;
  hasCreatePermission: boolean;
  hasDeletePermission: boolean;
  deletingAssetId: string;
  onUpload: (files: File[]) => void;
  onDeleteAsset: (assetId: string) => void;
  disabled: boolean;
};

const AssetSectionCard: React.FC<AssetSectionCardProps> = ({
  section,
  assets,
  uploadQueue,
  isUploading,
  isLoadingAssets,
  hasCreatePermission,
  hasDeletePermission,
  deletingAssetId,
  onUpload,
  onDeleteAsset,
  disabled,
}) => {
  const [isExpanded, setIsExpanded] = useState(false);

  const handleFileChange = (event: React.ChangeEvent<HTMLInputElement>) => {
    const files = Array.from(event.target.files || []);
    onUpload(files);
    event.currentTarget.value = '';
  };

  return (
    <CardBox className='h-full'>
      <div className='flex items-center justify-between gap-3 mb-4'>
        <h3 className='text-lg font-semibold'>{section.label}</h3>
        {!hasCreatePermission && (
          <p className='text-xs text-gray-500'>
            You do not have upload permission
          </p>
        )}
      </div>

      <input
        type='file'
        multiple
        accept={section.accept}
        className='w-full border border-gray-300 rounded px-2 py-2 mb-3 bg-white dark:bg-dark-800'
        disabled={isUploading || disabled || !hasCreatePermission}
        onChange={handleFileChange}
      />

      {isUploading && (
        <p className='text-sm text-gray-500 mb-3'>
          Uploading {section.label.toLowerCase()} in chunks...
        </p>
      )}

      <UploadProgressList items={uploadQueue} />

      {isLoadingAssets && (
        <p className='text-sm text-gray-500'>Loading assets...</p>
      )}

      {!isLoadingAssets && assets.length > 0 && (
        <button
          type='button'
          className='mb-2 text-xs underline'
          onClick={() => setIsExpanded((prev) => !prev)}
        >
          {isExpanded
            ? `Hide uploaded ${section.label.toLowerCase()}`
            : `Show uploaded ${section.label.toLowerCase()} (${assets.length})`}
        </button>
      )}

      {!isLoadingAssets && assets.length === 0 && (
        <p className='text-sm text-gray-500'>
          No uploaded {section.label.toLowerCase()}.
        </p>
      )}

      {!isLoadingAssets && assets.length > 0 && isExpanded && (
        <ul className='space-y-2'>
          {assets.map((asset) => (
            <li
              key={asset.id}
              className='flex items-center justify-between gap-2 p-2 border border-gray-200 dark:border-dark-700 rounded'
            >
              <a
                href={asset.cdn_url || '#'}
                target='_blank'
                rel='noreferrer'
                className='text-sm underline truncate'
              >
                {asset.name.replace(/^\[[^\]]+\]\s*/, '')}
              </a>
              <BaseButton
                color='danger'
                label='X'
                small
                disabled={deletingAssetId === asset.id || !hasDeletePermission}
                onClick={() => onDeleteAsset(asset.id)}
              />
            </li>
          ))}
        </ul>
      )}
    </CardBox>
  );
};

export default AssetSectionCard;
