import React, { useState, useEffect } from 'react';
import { App } from '../types';
import './AppCard.css';

interface AppCardProps {
  app: App;
  iconUrl?: string;           // base64 data URL from backend
  onLaunch: (app: App) => void;
  onEdit?: (app: App) => void;
  onDelete?: (app: App) => void;
  onContextMenu?: (app: App, e: React.MouseEvent) => void;
  isDragging?: boolean;
  isDragOver?: boolean;
  onDragStart?: (e: React.MouseEvent | React.TouchEvent) => void;
}

const AppCard: React.FC<AppCardProps> = ({
  app,
  iconUrl,
  onLaunch,
  onEdit,
  onDelete,
  onContextMenu,
  isDragging,
  isDragOver,
  onDragStart,
}) => {
  const [imgFailed, setImgFailed] = useState(false)

  // Reset error state when icon URL changes (e.g. after refresh).
  useEffect(() => {
    setImgFailed(false)
  }, [iconUrl])

  const handleClick = () => {
    if (!isDragging) onLaunch(app)
  }

  return (
    <div
      className={`app-card ${isDragging ? 'dragging' : ''} ${isDragOver ? 'drag-over' : ''}`}
      data-app-id={app.id}
      onClick={handleClick}
      onContextMenu={(e) => { e.preventDefault(); onContextMenu?.(app, e) }}
      onMouseDown={onDragStart}
      onTouchStart={onDragStart}
    >
      <div className="app-icon">
        {iconUrl && !imgFailed ? (
          <img src={iconUrl} alt={app.name} onError={() => setImgFailed(true)} />
        ) : (
          <div className="app-icon-placeholder">
            {app.name.charAt(0).toUpperCase()}
          </div>
        )}
      </div>
      <div className="app-name" title={app.name}>{app.name}</div>
      {app.description && (
        <div className="app-description" title={app.description}>{app.description}</div>
      )}
      <div className="app-actions" onClick={(e) => e.stopPropagation()}>
        {onEdit && (
          <button className="action-btn" onClick={() => onEdit(app)} title="编辑">✏️</button>
        )}
        {onDelete && (
          <button className="action-btn" onClick={() => onDelete(app)} title="删除">🗑️</button>
        )}
      </div>
    </div>
  );
};

export default React.memo(AppCard);

export const EmptyCard: React.FC = () => (
  <div className="app-card empty-card">
    <div className="empty-placeholder"></div>
  </div>
);
