import { useEffect, useState } from 'react';
import '../style/AppCard.css';
import { getIconUrl } from '../services/api';
import { FaEdit, FaTrash } from 'react-icons/fa';

function AppCard({ app, section, onEdit, onDelete }) {
  const [iconUrl, setIconUrl] = useState(null);

  useEffect(() => {
    if (app.icon) {
      getIconUrl(app.icon)
        .then((url) => setIconUrl(url))
        .catch((err) => console.error(`Failed to load icon for ${app.name}:`, err));
    }
  }, [app.icon, app.name]);

  return (
    <div className="app-card-wrapper">
      <a href={app.url} className="app-card" target="_blank" rel="noreferrer">
        <div className="card-icons-inside">
          <FaTrash className="delete-icon" onClick={(e) => {
            e.preventDefault();
            if (typeof onDelete === 'function') {
              onDelete({ ...app, section });
            }
          }} />
          <FaEdit className="edit-icon" onClick={(e) => {
            e.preventDefault();
            if (typeof onEdit === 'function') {
              onEdit({ ...app, section });
            }
          }} />
        </div>
        <div className="app-icon-wrapper">
          {iconUrl ? <img src={iconUrl} alt={app.name} className="app-icon" /> : <span className="icon-placeholder">⚠️</span>}
        </div>
        <h3>{app.name}</h3>
        <p>{app.description}</p>
      </a>
    </div>
  );
}

export default AppCard;