import { useState, useEffect } from 'react';
import { useParams, Link } from 'react-router-dom';
import { Grove, Tree } from '../types';
import { getGrove, listTrees, createTree } from '../api';
import './Home.css';

function GrovePage() {
  const { groveName } = useParams<{ groveName: string }>();
  const [grove, setGrove] = useState<Grove | null>(null);
  const [trees, setTrees] = useState<Tree[]>([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);
  const [showForm, setShowForm] = useState(false);
  const [newTree, setNewTree] = useState({ name: '', description: '' });
  const [creating, setCreating] = useState(false);

  useEffect(() => {
    if (groveName) {
      loadData();
    }
  }, [groveName]);

  async function loadData() {
    try {
      setLoading(true);
      const [groveData, treesData] = await Promise.all([
        getGrove(groveName!),
        listTrees(groveName!),
      ]);
      setGrove(groveData);
      setTrees(treesData);
      setError(null);
    } catch (err) {
      setError(err instanceof Error ? err.message : 'Failed to load data');
    } finally {
      setLoading(false);
    }
  }

  async function handleCreateTree(e: React.FormEvent) {
    e.preventDefault();
    try {
      setCreating(true);
      await createTree(groveName!, newTree);
      setNewTree({ name: '', description: '' });
      setShowForm(false);
      loadData();
    } catch (err) {
      setError(err instanceof Error ? err.message : 'Failed to create tree');
    } finally {
      setCreating(false);
    }
  }

  if (loading) {
    return <div className="loading">Loading...</div>;
  }

  if (!grove) {
    return <div className="error-message">Grove not found</div>;
  }

  return (
    <div className="home">
      <nav className="breadcrumb">
        <Link to="/">Groves</Link> / <span>{grove.name}</span>
      </nav>

      <div className="page-header">
        <div>
          <h1>{grove.name}</h1>
          {grove.description && <p className="description">{grove.description}</p>}
        </div>
        <button className="btn btn-primary" onClick={() => setShowForm(!showForm)}>
          {showForm ? 'Cancel' : '+ New Tree'}
        </button>
      </div>

      {error && <div className="error-message">{error}</div>}

      {showForm && (
        <form className="form card" onSubmit={handleCreateTree}>
          <h3>Create New Tree</h3>
          <div className="form-group">
            <label htmlFor="name">Name</label>
            <input
              id="name"
              type="text"
              value={newTree.name}
              onChange={(e) => setNewTree({ ...newTree, name: e.target.value })}
              placeholder="releases"
              required
            />
          </div>
          <div className="form-group">
            <label htmlFor="description">Description</label>
            <input
              id="description"
              type="text"
              value={newTree.description}
              onChange={(e) => setNewTree({ ...newTree, description: e.target.value })}
              placeholder="Optional description"
            />
          </div>
          <button type="submit" className="btn btn-primary" disabled={creating}>
            {creating ? 'Creating...' : 'Create Tree'}
          </button>
        </form>
      )}

      {trees.length === 0 ? (
        <div className="empty-state">
          <p>No trees yet. Create your first tree to start uploading artifacts!</p>
        </div>
      ) : (
        <div className="grove-grid">
          {trees.map((tree) => (
            <Link to={`/grove/${groveName}/${tree.name}`} key={tree.id} className="grove-card card">
              <h3>📦 {tree.name}</h3>
              {tree.description && <p>{tree.description}</p>}
              <div className="grove-meta">
                <span className="date">
                  Created {new Date(tree.created_at).toLocaleDateString()}
                </span>
              </div>
            </Link>
          ))}
        </div>
      )}
    </div>
  );
}

export default GrovePage;
