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

const TASK_TYPES = [
  // P9.6: 'story' removed — all story/* types are restricted; must come from Proposal Accept workflow
  { value: 'issue', label: 'Issue', subtypes: ['infrastructure', 'performance', 'regression', 'security', 'user_experience', 'defect'] },
  // P7.1: 'task' type removed — defect subtype migrated to issue/defect
  { value: 'test', label: 'Test', subtypes: ['regression', 'security', 'smoke', 'stress'] },
  { value: 'maintenance', label: 'Maintenance', subtypes: ['deploy'] },  // P9.6: 'release' removed — controlled via milestone flow
  { value: 'research', label: 'Research', subtypes: [] },
  { value: 'review', label: 'Review', subtypes: ['code_review', 'decision_review', 'function_review'] },
  { value: 'resolution', label: 'Resolution', subtypes: [] },
]

export default function CreateTaskPage() {
  const navigate = useNavigate()
  const [projects, setProjects] = useState<Project[]>([])
  const [milestones, setMilestones] = useState<Milestone[]>([])
  const [form, setForm] = useState({
    title: '', description: '', project_code: '', milestone_code: '', task_type: 'issue',  // P7.1: default changed from 'task' to 'issue'
    task_subtype: '', priority: 'medium', tags: '', reporter_id: 1,
  })

  useEffect(() => {
    api.get<Project[]>('/projects').then(({ data }) => {
      setProjects(data)
      if (data.length) {
        setForm((f) => ({ ...f, project_code: data[0].project_code || '' }))
        // Load milestones for the first project
        api.get<Milestone[]>(`/milestones?project_code=${data[0].project_code}`).then(({ data: ms }) => {
          setMilestones(ms)
          if (ms.length) setForm((f) => ({ ...f, milestone_code: ms[0].milestone_code || '' }))
        })
      }
    })
  }, [])

  const handleProjectChange = (projectCode: string) => {
    setForm(f => ({ ...f, project_code: projectCode, milestone_code: '' }))
    api.get<Milestone[]>(`/milestones?project_code=${projectCode}`).then(({ data: ms }) => {
      setMilestones(ms)
      if (ms.length) setForm((f) => ({ ...f, milestone_code: ms[0].milestone_code || '' }))
    })
  }

  const currentType = TASK_TYPES.find(t => t.value === form.task_type) || TASK_TYPES[2]
  const subtypes = currentType.subtypes || []

  const handleTypeChange = (newType: string) => {
    setForm(f => ({ ...f, task_type: newType, task_subtype: '' }))
  }

  const submit = async (e: React.FormEvent) => {
    e.preventDefault()
    if (!form.milestone_code) {
      alert('Please select a milestone')
      return
    }
    const payload: any = { ...form, tags: form.tags || null }
    if (!form.task_subtype) delete payload.task_subtype
    await api.post('/tasks', payload)
    navigate('/tasks')
  }

  return (
    <div className="create-task">
      <h2>Create Task</h2>
      <form onSubmit={submit}>
        <label>Title <input data-testid="task-title-input" required value={form.title} onChange={(e) => setForm({ ...form, title: e.target.value })} /></label>
        <label>Description <textarea data-testid="task-description-input" value={form.description} onChange={(e) => setForm({ ...form, description: e.target.value })} /></label>
        <label>Projects
          <select data-testid="project-select" value={form.project_code} onChange={(e) => handleProjectChange(e.target.value)}>
            {projects.map((p) => <option key={p.id} value={p.project_code || ''}>{p.name}</option>)}
          </select>
        </label>
        <label>Milestone
          <select data-testid="milestone-select" value={form.milestone_code} onChange={(e) => setForm({ ...form, milestone_code: e.target.value })}>
            {milestones.length === 0 && <option value="">No milestones available</option>}
            {milestones.map((m) => <option key={m.id} value={m.milestone_code || ''}>{m.title}</option>)}
          </select>
        </label>
        <label>Type
          <select data-testid="task-type-select" value={form.task_type} onChange={(e) => handleTypeChange(e.target.value)}>
            {TASK_TYPES.map((t) => <option key={t.value} value={t.value}>{t.label}</option>)}
          </select>
        </label>
        {subtypes.length > 0 && (
          <label>Subtype
            <select value={form.task_subtype} onChange={(e) => setForm({ ...form, task_subtype: e.target.value })}>
              <option value="">Select subtype</option>
              {subtypes.map((s) => <option key={s} value={s}>{s.replace('_', ' ')}</option>)}
            </select>
          </label>
        )}
        <label>Priority
          <select value={form.priority} onChange={(e) => setForm({ ...form, priority: e.target.value })}>
            <option value="low">Low</option>
            <option value="medium">Medium</option>
            <option value="high">High</option>
            <option value="critical">Critical</option>
          </select>
        </label>
        <label>Tags <input value={form.tags} onChange={(e) => setForm({ ...form, tags: e.target.value })} placeholder="Comma separated" /></label>
        <button data-testid="create-task-button" type="submit" className="btn-primary">Create</button>
      </form>
    </div>
  )
}
