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

export default function ReportsDashboard() {
  const [stats, setStats] = useState<any>(null);
  const [loading, setLoading] = useState(true);

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

  const loadStats = async () => {
    setLoading(true);
    try {
      const [tasksResult, projectsResult, timelogsResult] = await Promise.all([
        window.mcp.callTool('wrike_list_tasks', {}),
        window.mcp.callTool('wrike_list_projects', {}),
        window.mcp.callTool('wrike_list_timelogs', {}),
      ]);

      const tasks = tasksResult.tasks || [];
      const projects = projectsResult.projects || [];
      const timelogs = timelogsResult.timelogs || [];

      const tasksByStatus = tasks.reduce((acc: any, task: any) => {
        acc[task.status] = (acc[task.status] || 0) + 1;
        return acc;
      }, {});

      const projectsByStatus = projects.reduce((acc: any, project: any) => {
        const status = project.project?.status || 'Unknown';
        acc[status] = (acc[status] || 0) + 1;
        return acc;
      }, {});

      const totalHours = timelogs.reduce((sum: number, log: any) => sum + log.hours, 0);

      setStats({
        totalTasks: tasks.length,
        totalProjects: projects.length,
        totalHours,
        tasksByStatus,
        projectsByStatus,
      });
    } catch (error) {
      console.error('Failed to load stats:', error);
    } finally {
      setLoading(false);
    }
  };

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

      {loading ? (
        <div>Loading...</div>
      ) : stats && (
        <div>
          <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fit, minmax(250px, 1fr))', gap: '16px', marginBottom: '24px' }}>
            <div style={{
              background: '#1f2937',
              padding: '24px',
              borderRadius: '8px',
              border: '1px solid #374151',
            }}>
              <div style={{ fontSize: '36px', fontWeight: 'bold', color: '#3b82f6' }}>
                {stats.totalTasks}
              </div>
              <div style={{ color: '#9ca3af' }}>Total Tasks</div>
            </div>
            <div style={{
              background: '#1f2937',
              padding: '24px',
              borderRadius: '8px',
              border: '1px solid #374151',
            }}>
              <div style={{ fontSize: '36px', fontWeight: 'bold', color: '#10b981' }}>
                {stats.totalProjects}
              </div>
              <div style={{ color: '#9ca3af' }}>Total Projects</div>
            </div>
            <div style={{
              background: '#1f2937',
              padding: '24px',
              borderRadius: '8px',
              border: '1px solid #374151',
            }}>
              <div style={{ fontSize: '36px', fontWeight: 'bold', color: '#f59e0b' }}>
                {stats.totalHours.toFixed(1)}h
              </div>
              <div style={{ color: '#9ca3af' }}>Total Hours Logged</div>
            </div>
          </div>

          <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: '24px' }}>
            <div style={{
              background: '#1f2937',
              padding: '24px',
              borderRadius: '8px',
              border: '1px solid #374151',
            }}>
              <h2 style={{ fontSize: '18px', fontWeight: '600', marginBottom: '16px' }}>
                Tasks by Status
              </h2>
              <div style={{ display: 'grid', gap: '8px' }}>
                {Object.entries(stats.tasksByStatus).map(([status, count]: any) => (
                  <div key={status} style={{ display: 'flex', justifyContent: 'space-between' }}>
                    <span>{status}</span>
                    <span style={{ fontWeight: 'bold', color: '#3b82f6' }}>{count}</span>
                  </div>
                ))}
              </div>
            </div>

            <div style={{
              background: '#1f2937',
              padding: '24px',
              borderRadius: '8px',
              border: '1px solid #374151',
            }}>
              <h2 style={{ fontSize: '18px', fontWeight: '600', marginBottom: '16px' }}>
                Projects by Status
              </h2>
              <div style={{ display: 'grid', gap: '8px' }}>
                {Object.entries(stats.projectsByStatus).map(([status, count]: any) => (
                  <div key={status} style={{ display: 'flex', justifyContent: 'space-between' }}>
                    <span>{status}</span>
                    <span style={{ fontWeight: 'bold', color: '#10b981' }}>{count}</span>
                  </div>
                ))}
              </div>
            </div>
          </div>
        </div>
      )}
    </div>
  );
}
