import { useState, useEffect } from 'react'
import { useNavigate } from 'react-router-dom'
import api from '@/services/api'
import type { Project } from '@/types'
import dayjs from 'dayjs'

export default function ProjectsPage() {
  const [projects, setProjects] = useState<Project[]>([])
  const [showCreate, setShowCreate] = useState(false)
  const [form, setForm] = useState({ name: '', description: '', owner_id: 1 })
  const navigate = useNavigate()

  const fetchProjects = () => {
    api.get<Project[]>('/projects').then(({ data }) => setProjects(data))
  }

  useEffect(() => { fetchProjects() }, [])

  const createProject = async (e: React.FormEvent) => {
    e.preventDefault()
    await api.post('/projects', form)
    setForm({ name: '', description: '', owner_id: 1 })
    setShowCreate(false)
    fetchProjects()
  }

  return (
    <div className="projects-page">
      <div className="page-header">
        <h2>📁 Projects ({projects.length})</h2>
        <button className="btn-primary" onClick={() => setShowCreate(!showCreate)}>
          {showCreate ? 'Cancel' : '+ NewProjects'}
        </button>
      </div>

      {showCreate && (
        <form className="inline-form" onSubmit={createProject}>
          <input
            required placeholder="Project name" value={form.name}
            onChange={(e) => setForm({ ...form, name: e.target.value })}
          />
          <input
            placeholder="ProjectsDescription (optional)" value={form.description}
            onChange={(e) => setForm({ ...form, description: e.target.value })}
          />
          <button type="submit" className="btn-primary">Create</button>
        </form>
      )}

      <div className="project-grid">
        {projects.map((p) => (
          <div key={p.id} className="project-card" onClick={() => navigate(`/projects/${p.id}`)}>
            <h3>{p.name}</h3>{p.project_code && <span className=badge style={{ marginLeft: 8 }}>{p.project_code}</span>}
            <p className="project-desc">{p.description || 'No description'}</p>
            <div className="project-meta">
              <span>Created {dayjs(p.created_at).format('YYYY-MM-DD')}</span>
            </div>
          </div>
        ))}
        {projects.length === 0 && <p className="empty">No projects yet. Create one above.</p>}
      </div>
    </div>
  )
}
