"use client";

import { useRouter } from "next/navigation";
import { Home } 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 { ResidenceCard } from "@/components/residences/residence-card";
import { useResidences } from "@/lib/hooks/use-residences";
import { useDataProvider } from "@/lib/demo/data-provider-context";

export default function ResidencesPage() {
  const router = useRouter();
  const { basePath } = useDataProvider();
  const { data: residences, isLoading, error, refetch } = useResidences();

  return (
    <div className="space-y-6">
      <PageHeader
        title="Your Homes"
        description="All the places you look after"
        actionLabel="Add Home"
        onAction={() => router.push(`${basePath}/residences/new`)}
      />

      {isLoading && <LoadingSkeleton variant="card-grid" />}

      {error && (
        <ErrorBanner
          message="Failed to load residences."
          onRetry={() => refetch()}
        />
      )}

      {!isLoading && !error && Array.isArray(residences) && residences.length === 0 && (
        <EmptyState
          icon={Home}
          title="No homes added yet"
          description="Add your home to start keeping track of everything — tasks, documents, contractors, and more."
          actionLabel="Add Your Home"
          onAction={() => router.push(`${basePath}/residences/new`)}
        />
      )}

      {!isLoading && !error && Array.isArray(residences) && residences.length > 0 && (
        <div className="grid grid-cols-1 gap-5 sm:grid-cols-2 lg:grid-cols-3">
          {residences.map((item) => (
            <ResidenceCard key={item.residence.id} data={item} />
          ))}
        </div>
      )}
    </div>
  );
}
