import * as React from 'react';
import { Link } from 'react-router-dom';
import { api, type Project } from '../api';
import { useFetch } from '../hooks/useFetch';

export function ProjectsPage(): React.JSX.Element {
  const { data, error, loading } = useFetch(() => api.get<Project[]>('/api/v1/projects'));

  if (loading) return <div>Loading projects…</div>;
  if (error !== null) return <div style={{ color: '#ff7b72' }}>Error: {error.message}</div>;
  const projects = data ?? [];

  return (
    <section>
      <h2 style={{ marginTop: 0 }}>Projects</h2>
      <p style={{ color: '#7d8590' }}>Pick a project to edit its prompts.</p>
      {projects.length === 0 && <p>No projects yet.</p>}
      <ul style={{ listStyle: 'none', padding: 0, margin: 0 }}>
        {projects.map((p) => (
          <li key={p.id} style={{ padding: '8px 0', borderBottom: '1px solid #30363d' }}>
            <Link
              to={`/projects/${encodeURIComponent(p.name)}/prompts`}
              style={{ color: '#58a6ff', textDecoration: 'none', fontFamily: 'ui-monospace, "SF Mono", Menlo, monospace' }}
            >
              {p.name}
            </Link>
            {p.description !== undefined && p.description !== '' && (
              <span style={{ color: '#7d8590', marginLeft: 12 }}>{p.description}</span>
            )}
          </li>
        ))}
      </ul>
    </section>
  );
}
