"use client";

import React, { useEffect } from "react";
import { useRouter } from "next/navigation";
import { getApiErrorMessage } from "@/lib/api-error";
import { useGetTenantPropertyQuery } from "@/redux/api";
import { toast } from "sonner";
import type { ClientWorkspaceChildCtx } from "./client-workspace-layout";
import PropertyLayoutEditorForm from "./property-editor/property-layout-editor-form";

type Props = {
  ctx: ClientWorkspaceChildCtx;
  propertyId: string;
  listHref: string;
};

export default function ClientPropertyLayoutEdit({ ctx, propertyId, listHref }: Props) {
  const router = useRouter();
  const skip = !ctx.tenantReady || ctx.moduleBlockedProperty;

  const {
    data: row,
    isError,
    error,
    isLoading,
    isSuccess,
  } = useGetTenantPropertyQuery(
    { tenantKey: ctx.tenantApiKey, propertyId },
    { skip },
  );

  useEffect(() => {
    if (skip) return;
    if (isError) {
      toast.error(getApiErrorMessage(error, "Could not load property"));
      router.replace(listHref);
    }
  }, [skip, isError, error, listHref, router]);

  useEffect(() => {
    if (skip) return;
    if (isSuccess && row === null) {
      toast.error("Property not found");
      router.replace(listHref);
    }
  }, [skip, isSuccess, row, listHref, router]);

  if (ctx.moduleBlockedProperty) {
    return (
      <p className="rounded-md border border-amber-200 bg-amber-50 p-4 text-sm text-amber-900">
        The Property module is not enabled for this organization.
      </p>
    );
  }

  if (!ctx.tenantReady) {
    return <p className="text-sm text-gray-500">Loading workspace…</p>;
  }

  if (isLoading) {
    return <div className="p-6 text-center text-sm text-gray-500">Loading property…</div>;
  }

  if (!row) {
    return null;
  }

  return (
    <PropertyLayoutEditorForm
      ctx={ctx}
      property={row}
      listHref={listHref}
      onCancel={() => router.push(listHref)}
      onSaved={() => router.push(listHref)}
    />
  );
}
