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'
import ProjectFormModal from '@/components/ProjectFormModal'

export default function ProjectsPage() {
  const [projects, setProjects] = useState<Project[]>([])
  const [showCreate, setShowCreate] = useState(false)
  const navigate = useNavigate()

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

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

  return (
    <div className="projects-page">
      <div className="page-header">
        <h2>📁 Projects ({projects.length})</h2>
        <button className="btn-primary" onClick={() => setShowCreate(true)}>+ New</button>
      </div>

      <ProjectFormModal
        isOpen={showCreate}
        onClose={() => setShowCreate(false)}
        onSaved={() => fetchProjects()}
      />

      <div className="project-grid">
        {projects.map((p) => (
          <div key={p.id} className="project-card" onClick={() => navigate(`/projects/${p.project_code || 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>👤 {p.owner_name || 'Unknown'}</span>
              <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>
  )
}
