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

export default function GanttView() {
  const [tasks, setTasks] = useState<any[]>([]);
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    loadTasks();
  }, []);

  const loadTasks = async () => {
    setLoading(true);
    try {
      const result = await window.mcp.callTool('wrike_list_tasks', {});
      setTasks(result.tasks?.filter((t: any) => t.dates?.start && t.dates?.due) || []);
    } catch (error) {
      console.error('Failed to load tasks:', error);
    } finally {
      setLoading(false);
    }
  };

  const calculatePosition = (date: string) => {
    const minDate = Math.min(...tasks.map(t => new Date(t.dates.start).getTime()));
    const maxDate = Math.max(...tasks.map(t => new Date(t.dates.due).getTime()));
    const range = maxDate - minDate;
    const offset = new Date(date).getTime() - minDate;
    return (offset / range) * 100;
  };

  const calculateWidth = (start: string, due: string) => {
    const minDate = Math.min(...tasks.map(t => new Date(t.dates.start).getTime()));
    const maxDate = Math.max(...tasks.map(t => new Date(t.dates.due).getTime()));
    const range = maxDate - minDate;
    const duration = new Date(due).getTime() - new Date(start).getTime();
    return (duration / range) * 100;
  };

  return (
    <div style={{ background: '#111827', color: '#f3f4f6', minHeight: '100vh', padding: '24px' }}>
      <h1 style={{ fontSize: '24px', fontWeight: 'bold', marginBottom: '24px' }}>Gantt View</h1>
      
      <button
        onClick={loadTasks}
        style={{
          background: '#3b82f6',
          color: 'white',
          padding: '8px 16px',
          borderRadius: '6px',
          border: 'none',
          cursor: 'pointer',
          marginBottom: '24px',
        }}
      >
        Refresh
      </button>

      {loading ? (
        <div>Loading...</div>
      ) : tasks.length === 0 ? (
        <div>No tasks with dates found</div>
      ) : (
        <div>
          {tasks.map(task => (
            <div key={task.id} style={{ marginBottom: '16px' }}>
              <div style={{ fontSize: '14px', marginBottom: '4px' }}>{task.title}</div>
              <div style={{ position: 'relative', height: '30px', background: '#1f2937', borderRadius: '4px' }}>
                <div
                  style={{
                    position: 'absolute',
                    left: `${calculatePosition(task.dates.start)}%`,
                    width: `${calculateWidth(task.dates.start, task.dates.due)}%`,
                    height: '100%',
                    background: '#3b82f6',
                    borderRadius: '4px',
                    display: 'flex',
                    alignItems: 'center',
                    justifyContent: 'center',
                    fontSize: '12px',
                  }}
                >
                  {new Date(task.dates.start).toLocaleDateString()} - {new Date(task.dates.due).toLocaleDateString()}
                </div>
              </div>
            </div>
          ))}
        </div>
      )}
    </div>
  );
}
