import React, { useState, useEffect } from 'react';
import { useParams, useNavigate } from 'react-router-dom';
import { api } from '../../api/client';

export const TaskForm: React.FC = () => {
  const { id } = useParams<{ id: string }>();
  const navigate = useNavigate();
  const isEdit = !!id;

  // Form state
  const [title, setTitle] = useState('');
  const [description, setDescription] = useState('');
  const [status, setStatus] = useState('todo');
  const [assigned_to_id, setAssigned_to_id] = useState('');
  const [due_date, setDue_date] = useState('');
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState('');

  useEffect(() => {
    if (isEdit && id) {
      const loadTask = async () => {
        try {
          const data = await api.Task.get(id);
          setTitle(data.title || '');
          setDescription(data.description || '');
          setStatus(data.status || 'todo');
          setAssigned_to_id(data.assigned_to_id || '');
          setDue_date(data.due_date || '');
        } catch (error) {
          console.error('Failed to load Task:', error);
        }
      };
      loadTask();
    }
  }, [isEdit, id]);

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    setLoading(true);
    setError('');

    try {
      const data = {
        title,
        description,
        status,
        assigned_to_id,
        due_date,
      };

      if (isEdit && id) {
        await api.Task.update(id, data);
      } else {
        await api.Task.create(data);
      }
      navigate('/Tasks');
    } catch (error: any) {
      setError(error.message || 'Failed to save');
    } finally {
      setLoading(false);
    }
  };

  return (
    <div className="container mx-auto p-4">
      <h1 className="text-2xl font-bold mb-4">{isEdit ? 'Edit' : 'Create'} Task</h1>
      {error && <div className="alert alert-error mb-4">{error}</div>}
      <form onSubmit={handleSubmit} className="card p-6 space-y-4">
        <div>
          <label className="label">Title</label>
          <input
            type="text"
            className="input"
            value={title}
            onChange={(e) => setTitle(e.target.value)}
            required
          />
        </div>
        <div>
          <label className="label">Description</label>
          <textarea
            className="input"
            value={description}
            onChange={(e) => setDescription(e.target.value)}
            
          />
        </div>
        <div>
          <label className="label">Status</label>
          <select
            className="input"
            value={status}
            onChange={(e) => setStatus(e.target.value)}
            required
          >
            <option value="todo">todo</option>
            <option value="in_progress">in_progress</option>
            <option value="done">done</option>
          </select>
        </div>
        <div>
          <label className="label">Assigned_to_id</label>
          <input
            type="text"
            className="input"
            value={assigned_to_id}
            onChange={(e) => setAssigned_to_id(e.target.value)}
            
          />
        </div>
        <div>
          <label className="label">Due_date</label>
          <input
            type="date"
            className="input"
            value={due_date}
            onChange={(e) => setDue_date(e.target.value)}
            
          />
        </div>
        <div className="flex gap-2">
          <button type="submit" className="btn btn-primary" disabled={loading}>
            {loading ? 'Saving...' : 'Save'}
          </button>
          <button type="button" onClick={() => navigate('/Tasks')} className="btn btn-secondary">
            Cancel
          </button>
        </div>
      </form>
    </div>
  );
};
