import React, { useState, useEffect } from 'react';

export default function TaskDetail() {
  const [taskId, setTaskId] = useState('');
  const [task, setTask] = useState<any>(null);
  const [loading, setLoading] = useState(false);
  const [editing, setEditing] = useState(false);
  const [formData, setFormData] = useState({ title: '', description: '', status: '', importance: '' });

  const loadTask = async () => {
    if (!taskId) return;
    setLoading(true);
    try {
      const result = await window.mcp.callTool('wrike_get_task', { taskId });
      setTask(result.task);
      setFormData({
        title: result.task.title,
        description: result.task.description || '',
        status: result.task.status,
        importance: result.task.importance,
      });
    } catch (error) {
      console.error('Failed to load task:', error);
    } finally {
      setLoading(false);
    }
  };

  const updateTask = async () => {
    setLoading(true);
    try {
      await window.mcp.callTool('wrike_update_task', { taskId, ...formData });
      await loadTask();
      setEditing(false);
    } catch (error) {
      console.error('Failed to update task:', error);
    } finally {
      setLoading(false);
    }
  };

  return (
    <div style={{ background: '#111827', color: '#f3f4f6', minHeight: '100vh', padding: '24px' }}>
      <h1 style={{ fontSize: '24px', fontWeight: 'bold', marginBottom: '24px' }}>Task Detail</h1>

      <div style={{ marginBottom: '24px', display: 'flex', gap: '12px' }}>
        <input
          type="text"
          placeholder="Enter Task ID"
          value={taskId}
          onChange={(e) => setTaskId(e.target.value)}
          style={{
            flex: 1,
            background: '#1f2937',
            color: '#f3f4f6',
            padding: '8px 12px',
            borderRadius: '6px',
            border: '1px solid #374151',
          }}
        />
        <button
          onClick={loadTask}
          style={{
            background: '#3b82f6',
            color: 'white',
            padding: '8px 16px',
            borderRadius: '6px',
            border: 'none',
            cursor: 'pointer',
          }}
        >
          Load Task
        </button>
      </div>

      {loading && <div>Loading...</div>}

      {task && !editing && (
        <div style={{ background: '#1f2937', padding: '24px', borderRadius: '8px', border: '1px solid #374151' }}>
          <div style={{ display: 'flex', justifyContent: 'space-between', marginBottom: '16px' }}>
            <h2 style={{ fontSize: '20px', fontWeight: '600' }}>{task.title}</h2>
            <button
              onClick={() => setEditing(true)}
              style={{
                background: '#3b82f6',
                color: 'white',
                padding: '6px 12px',
                borderRadius: '6px',
                border: 'none',
                cursor: 'pointer',
              }}
            >
              Edit
            </button>
          </div>
          <div style={{ marginBottom: '12px', color: '#9ca3af' }}>
            <strong>Status:</strong> {task.status}
          </div>
          <div style={{ marginBottom: '12px', color: '#9ca3af' }}>
            <strong>Importance:</strong> {task.importance}
          </div>
          <div style={{ marginBottom: '12px', color: '#9ca3af' }}>
            <strong>Description:</strong> {task.description || 'No description'}
          </div>
          {task.dates && (
            <div style={{ marginTop: '16px', fontSize: '14px', color: '#9ca3af' }}>
              {task.dates.start && <div>Start: {new Date(task.dates.start).toLocaleDateString()}</div>}
              {task.dates.due && <div>Due: {new Date(task.dates.due).toLocaleDateString()}</div>}
            </div>
          )}
        </div>
      )}

      {editing && (
        <div style={{ background: '#1f2937', padding: '24px', borderRadius: '8px', border: '1px solid #374151' }}>
          <h2 style={{ fontSize: '20px', fontWeight: '600', marginBottom: '16px' }}>Edit Task</h2>
          <div style={{ display: 'grid', gap: '16px' }}>
            <input
              type="text"
              placeholder="Title"
              value={formData.title}
              onChange={(e) => setFormData({ ...formData, title: e.target.value })}
              style={{
                background: '#111827',
                color: '#f3f4f6',
                padding: '8px 12px',
                borderRadius: '6px',
                border: '1px solid #374151',
              }}
            />
            <textarea
              placeholder="Description"
              value={formData.description}
              onChange={(e) => setFormData({ ...formData, description: e.target.value })}
              rows={4}
              style={{
                background: '#111827',
                color: '#f3f4f6',
                padding: '8px 12px',
                borderRadius: '6px',
                border: '1px solid #374151',
              }}
            />
            <select
              value={formData.status}
              onChange={(e) => setFormData({ ...formData, status: e.target.value })}
              style={{
                background: '#111827',
                color: '#f3f4f6',
                padding: '8px 12px',
                borderRadius: '6px',
                border: '1px solid #374151',
              }}
            >
              <option value="Active">Active</option>
              <option value="Completed">Completed</option>
              <option value="Deferred">Deferred</option>
              <option value="Cancelled">Cancelled</option>
            </select>
            <div style={{ display: 'flex', gap: '12px' }}>
              <button
                onClick={updateTask}
                style={{
                  background: '#10b981',
                  color: 'white',
                  padding: '8px 16px',
                  borderRadius: '6px',
                  border: 'none',
                  cursor: 'pointer',
                }}
              >
                Save
              </button>
              <button
                onClick={() => setEditing(false)}
                style={{
                  background: '#6b7280',
                  color: 'white',
                  padding: '8px 16px',
                  borderRadius: '6px',
                  border: 'none',
                  cursor: 'pointer',
                }}
              >
                Cancel
              </button>
            </div>
          </div>
        </div>
      )}
    </div>
  );
}
