import { useState, useEffect } from 'react';
import { clickup } from '../lib/api';

function Avatar({ name, avatar, size = 28 }) {
  const initials = (name || '?').split(' ').map(w => w[0]).join('').slice(0, 2).toUpperCase();
  const colors = ['#378ADD','#1D9E75','#D85A30','#7F77DD','#BA7517','#D4537E'];
  const color  = colors[(name || '').charCodeAt(0) % colors.length];
  if (avatar) return <img src={avatar} alt={name} style={{ width: size, height: size, borderRadius: '50%', objectFit: 'cover' }} />;
  return (
    <div style={{ width: size, height: size, borderRadius: '50%', background: color, color: '#fff', fontSize: size * 0.36, fontWeight: 600, display: 'flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0 }}>
      {initials}
    </div>
  );
}

function MiniBar({ pct, color = 'var(--green)' }) {
  return (
    <div style={{ height: 4, borderRadius: 2, background: 'var(--surface2)', overflow: 'hidden', flex: 1 }}>
      <div style={{ height: '100%', width: pct + '%', background: color, borderRadius: 2, transition: 'width .4s' }} />
    </div>
  );
}

function ProjectBar({ project }) {
  const { total, done, inProgress, inReview, todo } = project;
  if (total === 0) return null;
  return (
    <div style={{ display: 'flex', height: 5, borderRadius: 3, overflow: 'hidden', background: 'var(--surface2)' }}>
      <div style={{ width: (done / total * 100) + '%',       background: 'var(--green)',  transition: 'width .4s' }} />
      <div style={{ width: (inProgress / total * 100) + '%', background: 'var(--blue)',   transition: 'width .4s' }} />
      <div style={{ width: (inReview / total * 100) + '%',   background: 'var(--amber)',  transition: 'width .4s' }} />
      <div style={{ width: (todo / total * 100) + '%',       background: 'var(--border2)',transition: 'width .4s' }} />
    </div>
  );
}

function StatChip({ label, value, color }) {
  return (
    <div style={{ textAlign: 'center', minWidth: 48 }}>
      <div style={{ fontSize: 15, fontWeight: 600, color: color || 'var(--text)' }}>{value ?? '—'}</div>
      <div style={{ fontSize: 10, color: 'var(--text3)', marginTop: 1 }}>{label}</div>
    </div>
  );
}

function hrs(h) {
  if (!h && h !== 0) return '—';
  if (h === 0) return '0h';
  return h >= 1 ? `${h}h` : `${Math.round(h * 60)}m`;
}

// ── Member card ───────────────────────────────────────────────
function MemberCard({ member, selected, onClick }) {
  return (
    <div onClick={onClick}
      style={{
        background: selected ? 'var(--blue-bg)' : 'var(--surface2)',
        border: `0.5px solid ${selected ? 'var(--blue)' : 'var(--border)'}`,
        borderRadius: 10, padding: '12px 14px', cursor: 'pointer',
        transition: 'all .15s',
      }}>
      <div style={{ display: 'flex', alignItems: 'center', gap: 10, marginBottom: 10 }}>
        <Avatar name={member.name} avatar={member.avatar} size={32} />
        <div>
          <div style={{ fontWeight: 500, fontSize: 13, color: 'var(--text)' }}>{member.name}</div>
          <div style={{ fontSize: 11, color: 'var(--text3)' }}>{member.email || ''}</div>
        </div>
      </div>
      <div style={{ display: 'flex', gap: 12, marginBottom: 8 }}>
        <StatChip label="Total"    value={member.totalTasks}    />
        <StatChip label="Done"     value={member.doneTasks}     color="var(--green-text)" />
        <StatChip label="Active"   value={member.inProgressTasks} color="var(--blue-text)" />
        <StatChip label="Overdue"  value={member.overdueTasks}  color={member.overdueTasks > 0 ? 'var(--red-text)' : undefined} />
      </div>
      <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
        <MiniBar pct={member.completionRate} />
        <span style={{ fontSize: 11, color: 'var(--text2)', whiteSpace: 'nowrap' }}>{member.completionRate}%</span>
      </div>
      {(member.timeSpentHours > 0) && (
        <div style={{ fontSize: 11, color: 'var(--text2)', marginTop: 6 }}>
          🕐 {hrs(member.timeSpentHours)} logged
          {member.timeEstimateHours > 0 && ` / ${hrs(member.timeEstimateHours)} est.`}
        </div>
      )}
    </div>
  );
}

// ── Main component ────────────────────────────────────────────
export default function TeamPanel({ folderIds }) {
  const [data, setData]             = useState(null);
  const [loading, setLoading]       = useState(true);
  const [error, setError]           = useState(null);
  const [selectedMember, setSelectedMember] = useState(null);
  const [activeSubTab, setActiveSubTab]     = useState('members'); // members | projects | time
  const [assigneeFilter, setAssigneeFilter] = useState(null); // member id

  useEffect(() => {
    setLoading(true);
    setData(null);
    clickup.teamOverview(folderIds)
      .then(d => { setData(d); setError(null); })
      .catch(e => setError(e.message))
      .finally(() => setLoading(false));
  }, [folderIds]);

  if (loading) return (
    <div>
      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fill,minmax(200px,1fr))', gap: 10 }}>
        {[0,1,2,3].map(i => <div key={i} className="skeleton" style={{ height: 120, borderRadius: 10 }} />)}
      </div>
    </div>
  );

  if (error || !data) return (
    <div style={{ fontSize: 12, color: 'var(--text2)', padding: '20px 0' }}>
      {error?.includes('401') || error?.includes('403')
        ? 'ClickUp API token is invalid or expired. Check CLICKUP_API_TOKEN in your .env.'
        : error?.includes('500') || !data
          ? 'ClickUp not connected. Add CLICKUP_API_TOKEN and CLICKUP_TEAM_ID to your .env file.'
          : `Error: ${error}`}
    </div>
  );

  const { members, projects, timeByMember, timeEntries, totals } = data;

  // Tasks for selected member (filtered from projects task list — re-fetch if needed)
  const subTabs = [
    { key: 'members',  label: `👥 Team (${members.length})` },
    { key: 'projects', label: `📁 Projects (${projects.length})` },
    { key: 'time',     label: `🕐 Time tracking` },
  ];

  return (
    <div>
      {/* Totals strip */}
      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(5,minmax(0,1fr))', gap: 8, marginBottom: 16 }}>
        {[
          { label: 'Total tasks',   value: totals.tasks,           color: null },
          { label: 'Done',          value: totals.done,            color: 'var(--green-text)' },
          { label: 'In progress',   value: totals.inProgress,      color: 'var(--blue-text)'  },
          { label: 'Overdue',       value: totals.overdue,         color: totals.overdue > 0 ? 'var(--red-text)' : null },
          { label: 'Time logged',   value: hrs(totals.timeSpentHours), color: null },
        ].map(s => (
          <div key={s.label} className="metric-card" style={{ padding: '10px 12px' }}>
            <div className="metric-label">{s.label}</div>
            <div className="metric-value" style={{ fontSize: 20, color: s.color || 'var(--text)' }}>{s.value}</div>
          </div>
        ))}
      </div>

      {/* Sub-tabs */}
      <div style={{ display: 'flex', gap: 4, marginBottom: 14, borderBottom: '0.5px solid var(--border)', paddingBottom: 0 }}>
        {subTabs.map(t => (
          <button key={t.key} onClick={() => setActiveSubTab(t.key)}
            style={{ fontSize: 12, padding: '6px 14px', borderRadius: '7px 7px 0 0', border: 'none', cursor: 'pointer',
              background: activeSubTab === t.key ? 'var(--surface)' : 'transparent',
              color: activeSubTab === t.key ? 'var(--text)' : 'var(--text2)',
              fontWeight: activeSubTab === t.key ? 500 : 400,
              borderBottom: activeSubTab === t.key ? '2px solid var(--blue)' : '2px solid transparent',
            }}>
            {t.label}
          </button>
        ))}
      </div>

      {/* ── Members tab ── */}
      {activeSubTab === 'members' && (
        <div>
          {members.length === 0
            ? <p style={{ fontSize: 12, color: 'var(--text2)' }}>No team members with assigned tasks found.</p>
            : (
              <div>
                {/* Assignee filter */}
                <div style={{ display: 'flex', gap: 6, flexWrap: 'wrap', marginBottom: 14 }}>
                  <button onClick={() => setAssigneeFilter(null)}
                    style={{ fontSize: 11, padding: '3px 10px', borderRadius: 20, cursor: 'pointer', border: '0.5px solid var(--border2)', background: !assigneeFilter ? 'var(--blue)' : 'transparent', color: !assigneeFilter ? '#fff' : 'var(--text2)' }}>
                    All members
                  </button>
                  {members.map(m => (
                    <button key={m.id} onClick={() => setAssigneeFilter(assigneeFilter === m.id ? null : m.id)}
                      style={{ fontSize: 11, padding: '3px 10px', borderRadius: 20, cursor: 'pointer', border: '0.5px solid var(--border2)',
                        background: assigneeFilter === m.id ? 'var(--blue)' : 'transparent',
                        color: assigneeFilter === m.id ? '#fff' : 'var(--text2)',
                        display: 'flex', alignItems: 'center', gap: 5 }}>
                      <Avatar name={m.name} avatar={m.avatar} size={14} />
                      {m.name}
                    </button>
                  ))}
                </div>

                <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fill,minmax(220px,1fr))', gap: 10 }}>
                  {(assigneeFilter ? members.filter(m => m.id === assigneeFilter) : members).map(m => (
                    <MemberCard key={m.id} member={m}
                      selected={selectedMember === m.id}
                      onClick={() => setSelectedMember(selectedMember === m.id ? null : m.id)} />
                  ))}
                </div>
              </div>
            )
          }
        </div>
      )}

      {/* ── Projects tab ── */}
      {activeSubTab === 'projects' && (
        <div>
          {projects.length === 0
            ? <p style={{ fontSize: 12, color: 'var(--text2)' }}>No projects found.</p>
            : (
              <div style={{ display: 'flex', flexDirection: 'column', gap: 10 }}>
                {projects.map(p => (
                  <div key={p.id} style={{ background: 'var(--surface2)', border: '0.5px solid var(--border)', borderRadius: 10, padding: '12px 16px' }}>
                    <div style={{ display: 'flex', alignItems: 'flex-start', justifyContent: 'space-between', marginBottom: 8 }}>
                      <div>
                        <div style={{ fontWeight: 500, fontSize: 13 }}>{p.name}</div>
                        {p.spaceName && <div style={{ fontSize: 11, color: 'var(--text3)', marginTop: 2 }}>{p.spaceName}</div>}
                      </div>
                      <div style={{ display: 'flex', gap: 12, alignItems: 'center' }}>
                        <StatChip label="Done"    value={p.done}       color="var(--green-text)" />
                        <StatChip label="Active"  value={p.inProgress} color="var(--blue-text)"  />
                        <StatChip label="To do"   value={p.todo}                                  />
                        {p.overdue > 0 && <StatChip label="Overdue" value={p.overdue} color="var(--red-text)" />}
                        <div style={{ textAlign: 'center', minWidth: 48 }}>
                          <div style={{ fontSize: 15, fontWeight: 600, color: p.pctDone >= 75 ? 'var(--green-text)' : p.pctDone >= 40 ? 'var(--amber-text)' : 'var(--text)' }}>{p.pctDone}%</div>
                          <div style={{ fontSize: 10, color: 'var(--text3)', marginTop: 1 }}>done</div>
                        </div>
                      </div>
                    </div>
                    <ProjectBar project={p} />
                    {(p.timeSpentHours > 0 || p.timeEstimateHours > 0) && (
                      <div style={{ fontSize: 11, color: 'var(--text2)', marginTop: 7 }}>
                        🕐 {hrs(p.timeSpentHours)} logged
                        {p.timeEstimateHours > 0 && ` · ${hrs(p.timeEstimateHours)} estimated`}
                        {p.timeEstimateHours > 0 && ` · ${Math.min(100, Math.round(p.timeSpentHours / p.timeEstimateHours * 100))}% of budget`}
                      </div>
                    )}
                  </div>
                ))}
              </div>
            )
          }
        </div>
      )}

      {/* ── Time tracking tab ── */}
      {activeSubTab === 'time' && (
        <div>
          {/* Per-member time summary */}
          {timeByMember.length > 0 ? (
            <div>
              <div style={{ fontSize: 12, color: 'var(--text2)', marginBottom: 10 }}>Last 30 days</div>
              <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fill,minmax(180px,1fr))', gap: 8, marginBottom: 16 }}>
                {timeByMember.map(m => (
                  <div key={m.userId} style={{ background: 'var(--surface2)', border: '0.5px solid var(--border)', borderRadius: 10, padding: '10px 14px' }}>
                    <div style={{ display: 'flex', alignItems: 'center', gap: 8, marginBottom: 6 }}>
                      <Avatar name={m.userName} size={24} />
                      <span style={{ fontSize: 12, fontWeight: 500 }}>{m.userName}</span>
                    </div>
                    <div style={{ fontSize: 20, fontWeight: 600, color: 'var(--blue-text)' }}>{hrs(m.totalHours)}</div>
                    <div style={{ fontSize: 11, color: 'var(--text3)', marginTop: 2 }}>{m.entries.length} entries</div>
                  </div>
                ))}
              </div>

              {/* Recent time entries table */}
              <div style={{ fontSize: 12, fontWeight: 500, marginBottom: 8 }}>Recent entries</div>
              <table style={{ width: '100%', borderCollapse: 'collapse' }}>
                <thead>
                  <tr>
                    {['Person','Task','Duration','Date','Note'].map(h => (
                      <th key={h} style={{ fontSize: 11, fontWeight: 500, color: 'var(--text2)', textAlign: 'left', padding: '0 8px 8px', borderBottom: '0.5px solid var(--border)' }}>{h}</th>
                    ))}
                  </tr>
                </thead>
                <tbody>
                  {timeEntries.slice(0, 30).map(e => (
                    <tr key={e.id} style={{ borderBottom: '0.5px solid var(--border)' }}>
                      <td style={{ padding: '7px 8px', fontSize: 12 }}>
                        <div style={{ display: 'flex', alignItems: 'center', gap: 6 }}>
                          <Avatar name={e.userName} size={20} />
                          {e.userName}
                        </div>
                      </td>
                      <td style={{ padding: '7px 8px', fontSize: 12, color: 'var(--text2)', maxWidth: 200, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>{e.taskName || '—'}</td>
                      <td style={{ padding: '7px 8px', fontSize: 12, fontWeight: 500, color: 'var(--blue-text)' }}>{hrs(e.duration)}</td>
                      <td style={{ padding: '7px 8px', fontSize: 11, color: 'var(--text3)', whiteSpace: 'nowrap' }}>{e.start?.slice(0, 10) || '—'}</td>
                      <td style={{ padding: '7px 8px', fontSize: 11, color: 'var(--text3)' }}>{e.description || '—'}</td>
                    </tr>
                  ))}
                </tbody>
              </table>
            </div>
          ) : (
            <div style={{ fontSize: 12, color: 'var(--text2)', padding: '16px 0' }}>
              No time entries found for the last 30 days. Make sure time tracking is enabled in your ClickUp workspace and your plan supports the time tracking API.
            </div>
          )}
        </div>
      )}
    </div>
  );
}
