"use client";

import { use } from "react";
import { useRouter } from "next/navigation";
import { toast } from "sonner";

import { PageHeader } from "@/components/shared/page-header";
import { LoadingSkeleton } from "@/components/shared/loading-skeleton";
import { ErrorBanner } from "@/components/shared/error-banner";
import { ResidenceForm } from "@/components/residences/residence-form";
import { useResidence, useUpdateResidence } from "@/lib/hooks/use-residences";
import { useDataProvider } from "@/lib/demo/data-provider-context";

interface EditResidencePageProps {
  params: Promise<{ id: string }>;
}

export default function EditResidencePage({ params }: EditResidencePageProps) {
  const { id: rawId } = use(params);
  const id = Number(rawId);
  const router = useRouter();
  const { basePath } = useDataProvider();

  const { data: residence, isLoading, error, refetch } = useResidence(id);
  const updateResidence = useUpdateResidence(id);

  if (isLoading) {
    return (
      <div className="space-y-6">
        <LoadingSkeleton variant="detail" />
      </div>
    );
  }

  if (error || !residence) {
    return (
      <div className="space-y-6">
        <ErrorBanner
          message="Failed to load residence."
          onRetry={() => refetch()}
        />
      </div>
    );
  }

  return (
    <div className="space-y-6 w-full max-w-2xl mx-auto">
      <PageHeader
        title="Edit Residence"
        description={residence.name}
      />

      <ResidenceForm
        residence={residence}
        loading={updateResidence.isPending}
        onSubmit={(data) => {
          updateResidence.mutate(data, {
            onSuccess: () => {
              toast.success("Residence updated");
              router.push(`${basePath}/residences/${id}`);
            },
            onError: () => {
              toast.error("Failed to update residence");
            },
          });
        }}
      />
    </div>
  );
}
