import React, { useEffect, useState } from 'react';
import { fetchClients } from './apiClients';
import type { Client } from './apiClients';

const Dashboard: React.FC = () => {
  const [clients, setClients] = useState<Client[]>([]);

  useEffect(() => {
    fetchClients().then(setClients).catch(console.error);
  }, []);
  
  return (
    <div>
      <header className="mb-8 pb-4 border-b-2 border-[#d6c3a6]">
        <h2 className="text-3xl font-extrabold mb-2">Dashboard</h2>
      </header>
      <h3 className="text-lg font-semibold mt-6 mb-4">Infoscreens</h3>
      <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
        {clients.map(client => (
          <div key={client.uuid} className="bg-white rounded shadow p-4 flex flex-col items-center">
            <h4 className="text-lg font-bold mb-2">{client.location || 'Unbekannter Standort'}</h4>
            <img
              src={`/screenshots/${client.uuid}`}
              alt={`Screenshot ${client.location}`}
              className="w-full h-48 object-contain bg-gray-100 mb-2"
              onError={e => (e.currentTarget.style.display = 'none')}
            />
            <div className="text-sm text-gray-700 mb-1">
              <span className="font-semibold">IP:</span> {client.ip_address}
            </div>
            <div className="text-sm text-gray-700">
              <span className="font-semibold">Letztes Lebenszeichen:</span>{' '}
              {client.last_alive ? new Date(client.last_alive).toLocaleString() : '-'}
            </div>
          </div>
        ))}
        {clients.length === 0 && (
          <div className="col-span-full text-center text-gray-400">Keine Clients gefunden.</div>
        )}
      </div>
    </div>
  );
};

export default Dashboard;
