/**
 * File grid for DMS file browser.
 * Displays files with icons, names, sizes, and action buttons.
 */

import React, { useMemo } from 'react';
import clsx from 'clsx';
import { useTranslation } from 'react-i18next';
import type { DmsFile } from '@/api/dms';

function getFileIcon(mimeType: string): { path: string; color: string } {
  if (mimeType === 'application/pdf') {
    return { path: 'M9 12h6m-6 4h6m2 5H7a2 2 0 01-2-2V5a2 2 0 012-2h5.586a1 1 0 01.707.293l5.414 5.414a1 1 0 01.293.707V19a2 2 0 01-2 2z', color: 'text-danger-500' };
  }
  if (mimeType.startsWith('image/')) {
    return { path: 'M4 16l4.586-4.586a2 2 0 012.828 0L16 16m-2-2l1.586-1.586a2 2 0 012.828 0L20 14m-6-6h.01M6 20h12a2 2 0 002-2V6a2 2 0 00-2-2H6a2 2 0 00-2 2v12a2 2 0 002 2z', color: 'text-accent-500' };
  }
  if (mimeType.includes('spreadsheet') || mimeType.includes('excel')) {
    return { path: 'M9 17v-2m3 2v-4m3 4v-6m2 10H7a2 2 0 01-2-2V5a2 2 0 012-2h5.586a1 1 0 01.707.293l5.414 5.414a1 1 0 01.293.707V19a2 2 0 01-2 2z', color: 'text-success-500' };
  }
  if (mimeType.includes('presentation') || mimeType.includes('powerpoint')) {
    return { path: 'M7 8h10M7 16h10M7 12h6m-7 8h12a2 2 0 002-2V6a2 2 0 00-2-2H6a2 2 0 00-2 2v12a2 2 0 002 2z', color: 'text-warning-500' };
  }
  if (mimeType.startsWith('text/') || mimeType.includes('document') || mimeType.includes('word')) {
    return { path: 'M9 12h6m-6 4h6m2 5H7a2 2 0 01-2-2V5a2 2 0 012-2h5.586a1 1 0 01.707.293l5.414 5.414a1 1 0 01.293.707V19a2 2 0 01-2 2z', color: 'text-primary-500' };
  }
  if (mimeType.includes('zip') || mimeType.includes('compressed') || mimeType.includes('archive')) {
    return { path: 'M5 8h14M5 8a2 2 0 110-4h14a2 2 0 110 4M5 8v10a2 2 0 002 2h10a2 2 0 002-2V8m-9 4h4', color: 'text-secondary-500' };
  }
  return { path: 'M7 21h10a2 2 0 002-2V9.414a1 1 0 00-.293-.707l-5.414-5.414A1 1 0 0012.586 3H7a2 2 0 00-2 2v14a2 2 0 002 2z', color: 'text-secondary-400' };
}

function formatFileSize(bytes: number): string {
  if (bytes < 1024) return `${bytes} B`;
  if (bytes < 1024 * 1024) return `${(bytes / 1024).toFixed(1)} KB`;
  if (bytes < 1024 * 1024 * 1024) return `${(bytes / (1024 * 1024)).toFixed(1)} MB`;
  return `${(bytes / (1024 * 1024 * 1024)).toFixed(1)} GB`;
}

export interface FileGridProps {
  files: DmsFile[];
  selectedFileIds: Set<string>;
  onToggleSelect: (fileId: string) => void;
  onFileClick: (file: DmsFile) => void;
  onFileShare: (file: DmsFile) => void;
  onFileDelete: (file: DmsFile) => void;
  onFilePreview: (file: DmsFile) => void;
  loading?: boolean;
}

export function FileGrid({
  files,
  selectedFileIds,
  onToggleSelect,
  onFileClick,
  onFileShare,
  onFileDelete,
  onFilePreview,
  loading = false,
}: FileGridProps) {
  const { t } = useTranslation();

  const sortedFiles = useMemo(() => {
    return [...files].sort((a, b) => a.name.localeCompare(b.name));
  }, [files]);

  if (loading) {
    return (
      <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 gap-4" data-testid="file-grid-loading">
        {[1, 2, 3, 4, 5, 6].map((i) => (
          <div key={i} className="bg-white rounded-lg border border-secondary-200 p-4 animate-pulse">
            <div className="h-12 w-12 bg-secondary-100 rounded mb-3" />
            <div className="h-4 bg-secondary-100 rounded mb-2" />
            <div className="h-3 bg-secondary-50 rounded w-1/2" />
          </div>
        ))}
      </div>
    );
  }

  if (files.length === 0) {
    return (
      <div className="text-center py-12" data-testid="file-grid-empty">
        <svg className="mx-auto h-12 w-12 text-secondary-300" fill="none" viewBox="0 0 24 24" stroke="currentColor" aria-hidden="true">
          <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={1.5} d="M7 21h10a2 2 0 002-2V9.414a1 1 0 00-.293-.707l-5.414-5.414A1 1 0 0012.586 3H7a2 2 0 00-2 2v14a2 2 0 002 2z" />
        </svg>
        <p className="mt-2 text-sm text-secondary-500">{t('dms.noFiles')}</p>
      </div>
    );
  }

  return (
    <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 gap-4" data-testid="file-grid">
      {sortedFiles.map((file) => {
        const icon = getFileIcon(file.mime_type);
        const isSelected = selectedFileIds.has(file.id);
        return (
          <div
            key={file.id}
            className={clsx(
              'bg-white rounded-lg border p-4 motion-safe:transition-all cursor-pointer',
              isSelected ? 'border-primary-500 ring-2 ring-primary-200' : 'border-secondary-200 hover:border-secondary-300 hover:shadow-sm'
            )}
            onClick={() => onFileClick(file)}
            data-testid={`file-card-${file.id}`}
          >
            <div className="flex items-start justify-between mb-3">
              <div className="flex items-center gap-2">
                <input
                  type="checkbox"
                  checked={isSelected}
                  onChange={() => onToggleSelect(file.id)}
                  onClick={(e) => e.stopPropagation()}
                  className="rounded border-secondary-300 text-primary-600 focus:ring-primary-500"
                  aria-label={t('dms.bulkSelect')}
                />
                <svg className={clsx('w-10 h-10', icon.color)} fill="none" viewBox="0 0 24 24" stroke="currentColor" aria-hidden="true">
                  <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={1.5} d={icon.path} />
                </svg>
              </div>
            </div>
            <p className="text-sm font-medium text-secondary-900 truncate" title={file.name}>{file.name}</p>
            <div className="mt-1 flex items-center gap-3 text-xs text-secondary-500">
              <span>{formatFileSize(file.size)}</span>
              {file.mime_type && <span className="truncate">{file.mime_type.split('/')[1]?.toUpperCase()}</span>}
            </div>
            <div className="mt-3 flex items-center gap-1">
              <button
                onClick={(e) => { e.stopPropagation(); onFilePreview(file); }}
                className="p-1.5 rounded text-secondary-400 hover:text-primary-600 hover:bg-primary-50 min-h-touch min-w-touch"
                aria-label={t('dms.preview')}
                title={t('dms.preview')}
              >
                <svg className="w-4 h-4" fill="none" viewBox="0 0 24 24" stroke="currentColor" aria-hidden="true">
                  <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M15 12a3 3 0 11-6 0 3 3 0 016 0z" />
                  <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M2.458 12C3.732 7.943 7.523 5 12 5c4.478 0 8.268 2.943 9.542 7-1.274 4.057-5.064 7-9.542 7-4.477 0-8.268-2.943-9.542-7z" />
                </svg>
              </button>
              <button
                onClick={(e) => { e.stopPropagation(); onFileShare(file); }}
                className="p-1.5 rounded text-secondary-400 hover:text-primary-600 hover:bg-primary-50 min-h-touch min-w-touch"
                aria-label={t('dms.share')}
                title={t('dms.share')}
              >
                <svg className="w-4 h-4" fill="none" viewBox="0 0 24 24" stroke="currentColor" aria-hidden="true">
                  <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M8.7 10.7l6.6-3.4M8.7 13.3l6.6 3.4M18 12a3 3 0 11-6 0 3 3 0 016 0zM9 12a3 3 0 11-6 0 3 3 0 016 0z" />
                </svg>
              </button>
              <button
                onClick={(e) => { e.stopPropagation(); onFileDelete(file); }}
                className="p-1.5 rounded text-secondary-400 hover:text-danger-600 hover:bg-danger-50 min-h-touch min-w-touch"
                aria-label={t('dms.delete')}
                title={t('dms.delete')}
              >
                <svg className="w-4 h-4" fill="none" viewBox="0 0 24 24" stroke="currentColor" aria-hidden="true">
                  <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M19 7l-.867 12.142A2 2 0 0116.138 21H7.862a2 2 0 01-1.995-1.858L5 7m5 4v6m4-6v6m1-10V4a1 1 0 00-1-1h-4a1 1 0 00-1 1v3M4 7h16" />
                </svg>
              </button>
            </div>
          </div>
        );
      })}
    </div>
  );
}
