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

export default function MilestonesPage() {
  const [milestones, setMilestones] = useState<Milestone[]>([])
  const [projects, setProjects] = useState<Project[]>([])
  const [projectFilter, setProjectFilter] = useState('')
  const [showCreate, setShowCreate] = useState(false)
  const [form, setForm] = useState({ 
    title: '', 
    description: '', 
    project_id: 0, 
    due_date: '',
    planned_release_date: '',
    status: 'open',
    depend_on_milestones: [] as string[],
    depend_on_tasks: [] as number[]
  })
  const navigate = useNavigate()

  const fetchMilestones = () => {
    const params = projectFilter ? `?project_id=${projectFilter}` : ''
    api.get<Milestone[]>(`/milestones${params}`).then(({ data }) => setMilestones(data))
  }

  useEffect(() => {
    api.get<Project[]>('/projects').then(({ data }) => {
      setProjects(data)
      if (data.length) setForm((f) => ({ ...f, project_id: data[0].id }))
    })
  }, [])

  useEffect(() => { fetchMilestones() }, [projectFilter])

  const createMilestone = async (e: React.FormEvent) => {
    e.preventDefault()
    const payload: Record<string, unknown> = { 
      title: form.title,
      description: form.description,
      project_id: form.project_id,
      status: form.status,
      due_date: form.due_date || null,
      planned_release_date: form.planned_release_date || null,
      depend_on_milestones: form.depend_on_milestones,
      depend_on_tasks: form.depend_on_tasks
    }
    await api.post('/milestones', payload)
    setShowCreate(false)
    fetchMilestones()
  }

  return (
    <div className="milestones-page">
      <div className="page-header">
        <h2>🏁 Milestones ({milestones.length})</h2>
        <button className="btn-primary" disabled={!projectFilter} onClick={() => setShowCreate(!showCreate)}>
          {showCreate ? 'Cancel' : '+ NewMilestones'}
        </button>
      </div>

      <div className="filters">
        <select value={projectFilter} onChange={(e) => setProjectFilter(e.target.value)}>
          <option value="">All projects</option>
          {projects.map((p) => <option key={p.id} value={p.id}>{p.name}</option>)}
        </select>
      </div>

      {showCreate && (
        <form className="inline-form" onSubmit={createMilestone}>
          <input required placeholder="MilestonesTitle" value={form.title}
            onChange={(e) => setForm({ ...form, title: e.target.value })} />
          <input placeholder="Description (optional)" value={form.description}
            onChange={(e) => setForm({ ...form, description: e.target.value })} />
          <select value={form.project_id} onChange={(e) => setForm({ ...form, project_id: Number(e.target.value) })}>
            {projects.map((p) => <option key={p.id} value={p.id}>{p.name}</option>)}
          </select>
          <select value={form.status} onChange={(e) => setForm({ ...form, status: e.target.value })}>
            <option value="open">Open</option>
            <option value="pending">Pending</option>
            <option value="deferred">Deferred</option>
            <option value="progressing">Progressing</option>
            <option value="closed">Closed</option>
          </select>
          <input type="date" value={form.due_date}
            onChange={(e) => setForm({ ...form, due_date: e.target.value })} />
          <input type="date" placeholder="Planned Release" value={form.planned_release_date}
            onChange={(e) => setForm({ ...form, planned_release_date: e.target.value })} />
          <button type="submit" className="btn-primary">Create</button>
        </form>
      )}

      <div className="milestone-grid">
        {milestones.map((ms) => (
          <div key={ms.id} className="milestone-card" onClick={() => navigate(`/milestones/${ms.id}`)}>
            <div className="milestone-card-header">
              <span className={`badge status-${ms.status === 'progressing' ? 'in_progress' : ms.status}`}>{ms.status}</span>
              <h3>{ms.title}</h3>
            </div>
            <p className="project-desc">{ms.description || 'No description'}</p>
            <div className="project-meta">
              {ms.planned_release_date && <span>Release: {dayjs(ms.planned_release_date).format('YYYY-MM-DD')}</span>}
              {ms.due_date && <span>Due: {dayjs(ms.due_date).format('YYYY-MM-DD')}</span>}
              <span>Created {dayjs(ms.created_at).format('YYYY-MM-DD')}</span>
            </div>
          </div>
        ))}
        {milestones.length === 0 && <p className="empty">No milestones</p>}
      </div>
    </div>
  )
}
