'use client';

import { useCallback, useEffect, useState } from 'react';
import { api } from '@/lib/api';
import { cn } from '@/lib/cn';
import type { Task } from '@/lib/types';
import { KanbanBoard } from '@/components/tasks/kanban-board';
import { TaskListView } from '@/components/tasks/task-list-view';

type ViewMode = 'list' | 'kanban';

export default function TasksPage(): React.ReactElement {
  const [tasks, setTasks] = useState<Task[]>([]);
  const [view, setView] = useState<ViewMode>('kanban');
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    api<Task[]>('/api/tasks')
      .then(setTasks)
      .catch(() => {})
      .finally(() => setLoading(false));
  }, []);

  const handleTaskClick = useCallback((task: Task) => {
    // Task detail view will be added in future iteration
    console.log('Task clicked:', task.id);
  }, []);

  return (
    <div>
      <div className="mb-6 flex items-center justify-between">
        <h1 className="text-2xl font-semibold">Tasks</h1>
        <div className="flex items-center gap-2">
          <div className="flex rounded-lg border border-surface-border">
            <button
              type="button"
              onClick={() => setView('list')}
              className={cn(
                'px-3 py-1.5 text-xs transition-colors',
                view === 'list'
                  ? 'bg-surface-elevated text-text-primary'
                  : 'text-text-muted hover:text-text-secondary',
              )}
            >
              List
            </button>
            <button
              type="button"
              onClick={() => setView('kanban')}
              className={cn(
                'px-3 py-1.5 text-xs transition-colors',
                view === 'kanban'
                  ? 'bg-surface-elevated text-text-primary'
                  : 'text-text-muted hover:text-text-secondary',
              )}
            >
              Kanban
            </button>
          </div>
        </div>
      </div>

      {loading ? (
        <p className="py-8 text-center text-sm text-text-muted">Loading tasks...</p>
      ) : view === 'kanban' ? (
        <KanbanBoard tasks={tasks} onTaskClick={handleTaskClick} />
      ) : (
        <TaskListView tasks={tasks} onTaskClick={handleTaskClick} />
      )}
    </div>
  );
}
