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

const COLS = [
  { key: 'todo',       label: 'To do',      cls: 'todo'   },
  { key: 'inProgress', label: 'In progress', cls: 'inprog' },
  { key: 'inReview',   label: 'In review',   cls: 'review' },
  { key: 'done',       label: 'Done',        cls: 'done'   },
];

const PAGE_SIZE = 10;

function priorityDot(priority) {
  const colors = { urgent: '#E24B4A', high: '#EF9F27', normal: '#378ADD', low: '#888780' };
  return (
    <span style={{ display: 'inline-block', width: 6, height: 6, borderRadius: '50%', background: colors[priority] || colors.normal, marginRight: 5, flexShrink: 0 }} />
  );
}

function KanbanColumn({ col, tasks = [], onStatusChange, updating }) {
  const [visible, setVisible] = useState(PAGE_SIZE);
  const shown   = tasks.slice(0, visible);
  const remaining = tasks.length - visible;

  return (
    <div>
      {/* Column header */}
      <div style={{ fontSize: 11, fontWeight: 500, color: 'var(--text2)', marginBottom: 8, textTransform: 'uppercase', letterSpacing: '.04em', display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
        <span>{col.label}</span>
        <span style={{ fontWeight: 400 }}>{tasks.length}</span>
      </div>

      {/* Task cards */}
      {shown.map(task => (
        <div key={task.id} className={`tchip ${col.cls}`}
          style={{ opacity: updating === task.id ? 0.5 : 1, flexDirection: 'column', alignItems: 'flex-start', gap: 4, transition: 'opacity .15s' }}>
          <div style={{ display: 'flex', alignItems: 'center', width: '100%' }}>
            {priorityDot(task.priority)}
            <span style={{ flex: 1, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap', fontSize: 11 }}>{task.name}</span>
          </div>
          {task.dueDate && (
            <div style={{ fontSize: 10, opacity: 0.8, paddingLeft: 11 }}>
              Due {task.dueDate}
              {new Date(task.dueDate) < new Date() && col.key !== 'done' && (
                <span style={{ color: '#E24B4A', marginLeft: 4 }}>overdue</span>
              )}
            </div>
          )}
          {task.assignees?.length > 0 && (
            <div style={{ fontSize: 10, opacity: 0.7, paddingLeft: 11 }}>
              {task.assignees.map(a => a.name).join(', ')}
            </div>
          )}
          <div style={{ display: 'flex', gap: 4, paddingLeft: 11, flexWrap: 'wrap' }}>
            {COLS.filter(c => c.key !== col.key).map(c => (
              <button key={c.key} onClick={() => onStatusChange(task.id, c.key)}
                style={{ fontSize: 9, padding: '1px 5px', borderRadius: 3, border: '0.5px solid currentColor', background: 'transparent', cursor: 'pointer', opacity: 0.7 }}>
                → {c.label}
              </button>
            ))}
          </div>
        </div>
      ))}

      {/* Empty state */}
      {tasks.length === 0 && (
        <div style={{ fontSize: 11, color: 'var(--text3)', padding: '8px 0', textAlign: 'center' }}>Empty</div>
      )}

      {/* Show more / show less */}
      {tasks.length > PAGE_SIZE && (
        <div style={{ display: 'flex', gap: 6, marginTop: 6 }}>
          {remaining > 0 && (
            <button onClick={() => setVisible(v => v + PAGE_SIZE)}
              style={{ flex: 1, fontSize: 11, padding: '5px 0', borderRadius: 7, border: '0.5px solid var(--border2)', background: 'transparent', color: 'var(--blue-text)', cursor: 'pointer', fontWeight: 500 }}>
              +{Math.min(remaining, PAGE_SIZE)} more
            </button>
          )}
          {visible > PAGE_SIZE && (
            <button onClick={() => setVisible(PAGE_SIZE)}
              style={{ fontSize: 11, padding: '5px 8px', borderRadius: 7, border: '0.5px solid var(--border2)', background: 'transparent', color: 'var(--text3)', cursor: 'pointer' }}>
              Show less
            </button>
          )}
        </div>
      )}
    </div>
  );
}

export default function TasksKanban({ tasks, loading, onTaskUpdate }) {
  const [updating, setUpdating] = useState(null);

  const handleStatusChange = async (taskId, newStatus) => {
    setUpdating(taskId);
    try {
      await clickup.updateStatus(taskId, newStatus);
      onTaskUpdate?.();
    } catch { /* ignore */ }
    finally { setUpdating(null); }
  };

  if (loading) return <div className="skeleton" style={{ height: 200, borderRadius: 8 }} />;
  if (!tasks)  return <div style={{ color: 'var(--text2)', fontSize: 13, padding: '12px 0' }}>Configure ClickUp API token to see tasks.</div>;

  return (
    <div style={{ display: 'grid', gridTemplateColumns: 'repeat(4, minmax(0,1fr))', gap: 12 }}>
      {COLS.map(col => (
        <KanbanColumn
          key={col.key}
          col={col}
          tasks={tasks[col.key] || []}
          onStatusChange={handleStatusChange}
          updating={updating}
        />
      ))}
    </div>
  );
}
