import { useState, useEffect } from 'react';
import './styles.css';

export default function DeviceInventory() {
  const [devices, setDevices] = useState<any[]>([]);
  const [filteredDevices, setFilteredDevices] = useState<any[]>([]);
  const [typeFilter, setTypeFilter] = useState('all');
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    loadDevices();
  }, []);

  useEffect(() => {
    if (typeFilter === 'all') {
      setFilteredDevices(devices);
    } else {
      setFilteredDevices(devices.filter(d => d.type === typeFilter));
    }
  }, [typeFilter, devices]);

  const loadDevices = async () => {
    try {
      const response = await (window as any).mcp?.callTool('rippling_list_devices', { limit: 200 });
      const data = response?.devices || getSampleDevices();
      setDevices(data);
      setFilteredDevices(data);
    } catch (err) {
      setDevices(getSampleDevices());
      setFilteredDevices(getSampleDevices());
    } finally {
      setLoading(false);
    }
  };

  const getSampleDevices = () => [
    { id: '1', name: 'MacBook Pro 16"', type: 'LAPTOP', assignee: 'John Doe', serialNumber: 'ABC123', status: 'ASSIGNED' },
    { id: '2', name: 'iPhone 14 Pro', type: 'MOBILE', assignee: 'Jane Smith', serialNumber: 'XYZ789', status: 'ASSIGNED' },
    { id: '3', name: 'Dell Monitor 27"', type: 'MONITOR', assignee: null, serialNumber: 'MON456', status: 'AVAILABLE' },
    { id: '4', name: 'iPad Pro', type: 'TABLET', assignee: 'Bob Johnson', serialNumber: 'TAB321', status: 'ASSIGNED' },
  ];

  const types = ['all', ...Array.from(new Set(devices.map(d => d.type)))];

  if (loading) return <div className="container"><div className="loading">Loading devices...</div></div>;

  return (
    <div className="container">
      <div className="header">
        <h1>Device Inventory</h1>
        <p className="subtitle">{filteredDevices.length} devices</p>
      </div>

      <div className="filters">
        <select value={typeFilter} onChange={(e) => setTypeFilter(e.target.value)} className="filter-select">
          {types.map(type => (
            <option key={type} value={type}>{type === 'all' ? 'All Types' : type}</option>
          ))}
        </select>
      </div>

      <div className="device-grid">
        {filteredDevices.map(device => (
          <div key={device.id} className="device-card">
            <div className="device-icon">{device.type[0]}</div>
            <div className="device-info">
              <h3>{device.name}</h3>
              <p className="device-type">{device.type}</p>
              <p className="device-serial">SN: {device.serialNumber}</p>
              <p className="device-assignee">{device.assignee || 'Unassigned'}</p>
            </div>
            <span className={`device-status status-${device.status.toLowerCase()}`}>
              {device.status}
            </span>
          </div>
        ))}
      </div>
    </div>
  );
}
