import { useEffect, useState } from 'react';
import { api } from '../api';
import type { DepartmentInfo } from '../types';

export default function NewTask({ onCreated }: { onCreated: (id: string) => void }) {
  const [departments, setDepartments] = useState<DepartmentInfo[]>([]);
  const [title, setTitle] = useState('');
  const [description, setDescription] = useState('');
  const [department, setDepartment] = useState('');
  const [priority, setPriority] = useState('normal');
  const [error, setError] = useState('');

  useEffect(() => {
    api.listDepartments().then((data) => {
      setDepartments(data);
      if (data[0]) setDepartment(data[0].key);
    });
  }, []);

  async function submit() {
    setError('');
    if (!title.trim() || !department) {
      setError('العنوان والقسم مطلوبان / Title and department are required');
      return;
    }
    try {
      const task = await api.createTask({ title: title.trim(), description, department, priority });
      onCreated(task.id);
    } catch (err) {
      setError((err as Error).message);
    }
  }

  return (
    <div style={{ maxWidth: 480 }}>
      <h2>مهمة جديدة / New Task</h2>
      {error && <p style={{ color: '#ef4444' }}>{error}</p>}
      <label>العنوان / Title</label>
      <input value={title} onChange={(e) => setTitle(e.target.value)} />
      <label>الوصف / Description</label>
      <textarea rows={5} value={description} onChange={(e) => setDescription(e.target.value)} />
      <label>القسم / Department</label>
      <select value={department} onChange={(e) => setDepartment(e.target.value)}>
        {departments.map((d) => (
          <option key={d.key} value={d.key}>{d.label}</option>
        ))}
      </select>
      <label>الأولوية / Priority</label>
      <select value={priority} onChange={(e) => setPriority(e.target.value)}>
        <option value="low">low</option>
        <option value="normal">normal</option>
        <option value="high">high</option>
        <option value="urgent">urgent</option>
      </select>
      <button className="primary" onClick={submit}>إنشاء / Create</button>
    </div>
  );
}
