import React, { useState, useEffect } from 'react';
import api, { setAuthToken } from '../api';
import { ItemRead, ItemCreate } from '../types';

interface DashboardProps {
  token: string;
  onLogout: () => void;
}

const Dashboard: React.FC<DashboardProps> = ({ token, onLogout }) => {
  const [items, setItems] = useState<ItemRead[]>([]);
  const [title, setTitle] = useState('');
  const [description, setDescription] = useState('');
  const [error, setError] = useState<string | null>(null);

  useEffect(() => {
    setAuthToken(token);
    fetchItems();
  }, [token]);

  const fetchItems = async () => {
    try {
      const resp = await api.get('/items/');
      setItems(resp.data);
    } catch (err: any) {
      setError('Failed to load items');
    }
  };

  const handleCreate = async (e: React.FormEvent) => {
    e.preventDefault();
    try {
      const newItem: ItemCreate = { title, description };
      await api.post('/items/', newItem);
      setTitle('');
      setDescription('');
      fetchItems();
    } catch (err: any) {
      setError('Failed to create item');
    }
  };

  const handleLogout = () => {
    onLogout();
  };

  return (
    <div style={{ padding: '1rem' }}>
      <h2>Dashboard</h2>
      <button onClick={handleLogout}>Logout</button>
      {error && <p style={{ color: 'red' }}>{error}</p>}
      <form onSubmit={handleCreate} style={{ marginTop: '1rem' }}>
        <div>
          <input placeholder="Title" value={title} onChange={e => setTitle(e.target.value)} required />
        </div>
        <div>
          <input placeholder="Description" value={description} onChange={e => setDescription(e.target.value)} />
        </div>
        <button type="submit">Add Item</button>
      </form>
      <ul style={{ marginTop: '1rem' }}>
        {items.map(item => (
          <li key={item.id}>
            <strong>{item.title}</strong>: {item.description}
          </li>
        ))}
      </ul>
    </div>
  );
};

export default Dashboard;
