import { useState } from 'react'
import ProjectCard from './ProjectCard'
import ProjectModal from './ProjectModal'
import Button from '../UI/Button'
import useProjectStore from '../../store/useProjectStore'
import { deleteProject } from '../../api/projects'

export default function ProjectList() {
  const { projects, removeProject } = useProjectStore()
  const [showModal, setShowModal]   = useState(false)
  const [editing, setEditing]       = useState(null)

  const handleEdit   = (p) => { setEditing(p); setShowModal(true) }
  const handleDelete = async (p) => {
    if (window.confirm(`Delete "${p.name}" and all its deliverables?`)) {
      await deleteProject(p.id); removeProject(p.id)
    }
  }
  const handleClose = () => { setShowModal(false); setEditing(null) }

  return (
    <div className="flex flex-col h-full">
      <div className="flex items-center justify-between px-4 py-3 border-b border-surface-border flex-shrink-0">
        <h1 className="text-gold font-bold text-lg tracking-widest uppercase">FabDash</h1>
        <Button size="sm" onClick={() => setShowModal(true)}>+ Project</Button>
      </div>
      <div className="flex-1 overflow-y-auto p-3 space-y-2">
        {projects.length === 0 && (
          <div className="text-center py-10">
            <p className="text-text-muted text-sm">No projects yet.</p>
            <p className="text-text-muted/50 text-xs mt-1">Click "+ Project" to begin.</p>
          </div>
        )}
        {projects.map(p => (
          <ProjectCard key={p.id} project={p} onEdit={handleEdit} onDelete={handleDelete} />
        ))}
      </div>
      <ProjectModal isOpen={showModal} onClose={handleClose} project={editing} />
    </div>
  )
}
