"use client";

import { useState, useEffect } from "react";
import type { ReactElement } from "react";

import { TaskList } from "@/components/tasks/TaskList";
import { mockTasks } from "@/lib/api/tasks";
import type { Task } from "@mosaic/shared";

export default function TasksPage(): ReactElement {
  const [tasks, setTasks] = useState<Task[]>([]);
  const [isLoading, setIsLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);

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

  async function loadTasks(): Promise<void> {
    setIsLoading(true);
    setError(null);

    try {
      // TODO: Replace with real API call when backend is ready
      // const data = await fetchTasks();
      await new Promise((resolve) => setTimeout(resolve, 300));
      setTasks(mockTasks);
    } catch (err) {
      setError(
        err instanceof Error
          ? err.message
          : "We had trouble loading your tasks. Please try again when you're ready."
      );
    } finally {
      setIsLoading(false);
    }
  }

  return (
    <main className="container mx-auto px-4 py-8">
      <div className="mb-8">
        <h1 className="text-3xl font-bold text-gray-900">Tasks</h1>
        <p className="text-gray-600 mt-2">Organize your work at your own pace</p>
      </div>

      {error !== null ? (
        <div className="rounded-lg border border-amber-200 bg-amber-50 p-6 text-center">
          <p className="text-amber-800">{error}</p>
          <button
            onClick={() => void loadTasks()}
            className="mt-4 rounded-md bg-amber-600 px-4 py-2 text-sm font-medium text-white hover:bg-amber-700 transition-colors"
          >
            Try again
          </button>
        </div>
      ) : (
        <TaskList tasks={tasks} isLoading={isLoading} />
      )}
    </main>
  );
}
