"use client";

import { useState } from "react";
import { useRouter } from "next/navigation";
import dynamic from "next/dynamic";
import { ClipboardList } from "lucide-react";
import { PageHeader } from "@/components/shared/page-header";
import { LoadingSkeleton } from "@/components/shared/loading-skeleton";
import { ErrorBanner } from "@/components/shared/error-banner";
import { EmptyState } from "@/components/shared/empty-state";
import { LookupSelect } from "@/components/shared/lookup-select";
import { useTasks, useTasksByResidence } from "@/lib/hooks/use-tasks";

const KanbanBoard = dynamic(
  () => import("@/components/tasks/kanban-board").then((mod) => ({ default: mod.KanbanBoard })),
  { loading: () => <LoadingSkeleton variant="kanban" /> }
);
import { useResidences } from "@/lib/hooks/use-residences";
import { useDataProvider } from "@/lib/demo/data-provider-context";

export default function TasksPage() {
  const router = useRouter();
  const { basePath } = useDataProvider();
  const [selectedResidenceId, setSelectedResidenceId] = useState<
    number | undefined
  >();

  const { data: residences } = useResidences();
  const allTasks = useTasks();
  const filteredTasks = useTasksByResidence(selectedResidenceId ?? 0);

  const activeQuery = selectedResidenceId ? filteredTasks : allTasks;
  const { data, isLoading, isError, error, refetch } = activeQuery;

  const residenceItems = (Array.isArray(residences) ? residences : []).map((r) => ({
    id: r.residence.id,
    name: r.residence.name,
  }));

  const isEmpty =
    data && data.columns.every((col) => col.tasks.length === 0);

  return (
    <div className="space-y-6">
      <PageHeader
        title="Tasks"
        description="Everything on your to-do list"
        actionLabel="New Task"
        onAction={() => router.push(`${basePath}/tasks/new`)}
      >
        {residenceItems.length > 1 && (
          <LookupSelect
            items={[{ id: 0, name: "All Residences" }, ...residenceItems]}
            value={selectedResidenceId ?? 0}
            onValueChange={(v) =>
              setSelectedResidenceId(v === 0 ? undefined : v)
            }
            placeholder="Filter by residence..."
          />
        )}
      </PageHeader>

      {isLoading && <LoadingSkeleton variant="kanban" count={5} />}

      {isError && (
        <ErrorBanner
          message={error instanceof Error ? error.message : "Failed to load tasks"}
          onRetry={() => refetch()}
        />
      )}

      {!isLoading && !isError && isEmpty && (
        <EmptyState
          icon={ClipboardList}
          title="Nothing on the list yet"
          description="When something around the house needs attention, add it here and we'll help you stay on top of it."
          actionLabel="Add Your First Task"
          onAction={() => router.push(`${basePath}/tasks/new`)}
        />
      )}

      {!isLoading && !isError && data && !isEmpty && (
        <KanbanBoard data={data} />
      )}
    </div>
  );
}
