import type { PotentialDevice } from "../types";

interface PotentialDeviceCardProps {
  deviceId: string;
  group: PotentialDevice[];
  isExpanded: boolean;
  onToggleExpand: (deviceId: string) => void;
}

export const PotentialDeviceCard = ({
  deviceId,
  group,
  isExpanded,
  onToggleExpand,
}: PotentialDeviceCardProps) => {
  const latest = group.reduce((prev, current) =>
    prev.last_seen > current.last_seen ? prev : current
  );

  return (
    <div key={deviceId} className="card">
      <div className="card-header">
        <div>
          <h3 className="device-name">
            <span className="emoji">❓</span> {latest.class}
          </h3>
          <div className="device-meta">
            <span className="badge badge-protocol">{latest.protocol}</span>{" "}
            {latest.model}
          </div>
        </div>
      </div>
      <div className="card-content">
        <div className="device-meta">ID: {deviceId}</div>
        <div className="device-meta">
          Last seen: {new Date(latest.last_seen * 1000).toLocaleString()}
        </div>
        <div className="device-meta">Events: {group.length}</div>

        {isExpanded && (
          <div className="events-list">
            <h4>History</h4>
            {group
              .sort((a, b) => b.last_seen - a.last_seen)
              .map((event, idx) => (
                <div key={idx} className="event-item">
                  <div className="event-time">
                    {new Date(event.last_seen * 1000).toLocaleTimeString()}
                  </div>
                  <div className="event-data">{event.last_data}</div>
                </div>
              ))}
          </div>
        )}
      </div>
      <div className="actions">
        <button onClick={() => onToggleExpand(deviceId)}>
          {isExpanded ? "Collapse" : "Expand"}
        </button>
      </div>
    </div>
  );
};
