"use client";

import React, { useEffect, useState } from "react";
import Link from "next/link";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { cn } from "@/lib/utils";
import { getApiErrorMessage } from "@/lib/api-error";
import { useUpdateTenantPropertyMutation } from "@/redux/api";
import { toast } from "sonner";
import type { ClientWorkspaceChildCtx } from "@/features/client/client-workspace-layout";
import type { PropertyRow } from "@/features/client/property-types";

type Props = {
  ctx: ClientWorkspaceChildCtx;
  property: PropertyRow;
  listHref: string;
  onCancel: () => void;
  onSaved: () => void;
  /** Omit page chrome; use inside a dialog */
  embedded?: boolean;
};

export default function PropertyMaintenanceEditorForm({
  ctx,
  property,
  listHref,
  onCancel,
  onSaved,
  embedded = false,
}: Props) {
  const { tenantApiKey, tenantReady } = ctx;
  const [updateTenantProperty] = useUpdateTenantPropertyMutation();
  const [saving, setSaving] = useState(false);
  const [maintenanceChargeMode, setMaintenanceChargeMode] = useState<"fixed" | "per_sqft">(
    "fixed"
  );
  const [maintenanceChargeValue, setMaintenanceChargeValue] = useState("0");

  const fieldSuffix = property._id.replace(/[^a-zA-Z0-9]/g, "");

  useEffect(() => {
    setMaintenanceChargeMode(
      property.maintenanceChargeMode === "per_sqft" ? "per_sqft" : "fixed"
    );
    setMaintenanceChargeValue(String(property.maintenanceChargeValue ?? 0));
  }, [property._id, property.maintenanceChargeMode, property.maintenanceChargeValue]);

  const save = async () => {
    if (!tenantReady) {
      toast.error("Workspace not ready");
      return;
    }
    const maintenanceValueNum = Number(maintenanceChargeValue || 0);
    if (!Number.isFinite(maintenanceValueNum)) {
      toast.error("Maintenance charge value must be a number");
      return;
    }

    setSaving(true);
    try {
      await updateTenantProperty({
        tenantKey: tenantApiKey,
        propertyId: property._id,
        body: {
          maintenanceChargeMode,
          maintenanceChargeValue: maintenanceValueNum,
        },
      }).unwrap();
      toast.success("Maintenance charges updated");
      onSaved();
    } catch (e: unknown) {
      toast.error(getApiErrorMessage(e, "Could not save maintenance charges"));
    } finally {
      setSaving(false);
    }
  };

  const fields = (
    <div className="space-y-3 rounded-lg border border-gray-200 bg-white p-4">
      <Label className="text-sm font-medium text-gray-900">Charge type</Label>
      <div className="grid gap-2 sm:grid-cols-2">
        <label className="flex items-center gap-2 rounded border border-gray-200 bg-gray-50 px-3 py-2 text-sm">
          <input
            type="radio"
            name={`property-maintenance-mode-${fieldSuffix}`}
            checked={maintenanceChargeMode === "fixed"}
            onChange={() => setMaintenanceChargeMode("fixed")}
          />
          One Fixed
        </label>
        <label className="flex items-center gap-2 rounded border border-gray-200 bg-gray-50 px-3 py-2 text-sm">
          <input
            type="radio"
            name={`property-maintenance-mode-${fieldSuffix}`}
            checked={maintenanceChargeMode === "per_sqft"}
            onChange={() => setMaintenanceChargeMode("per_sqft")}
          />
          One Per Sq Feet
        </label>
      </div>
      <div>
        <Label htmlFor={`pe-maintenance-value-${fieldSuffix}`}>
          {maintenanceChargeMode === "fixed"
            ? "Fixed maintenance amount"
            : "Maintenance per sq feet"}
        </Label>
        <Input
          id={`pe-maintenance-value-${fieldSuffix}`}
          type="number"
          step="0.01"
          className="mt-1"
          value={maintenanceChargeValue}
          onChange={(e) => setMaintenanceChargeValue(e.target.value)}
        />
      </div>
    </div>
  );

  const actions = (
    <div className={cn("flex flex-col gap-2 sm:flex-row sm:flex-wrap", embedded ? "" : "border-t px-4 py-3 sm:px-6 sm:py-4")}>
      <Button
        variant="outline"
        className="w-full sm:w-auto"
        type="button"
        onClick={onCancel}
        disabled={saving}
      >
        Cancel
      </Button>
      <Button
        type="button"
        className="w-full sm:w-auto"
        onClick={() => void save()}
        disabled={saving || !tenantReady}
      >
        {saving ? "Saving…" : "Save"}
      </Button>
    </div>
  );

  if (embedded) {
    return (
      <div className="space-y-4">
        {fields}
        {actions}
      </div>
    );
  }

  return (
    <div className="min-w-0 overflow-hidden rounded-md border bg-white">
      <div className="border-b px-4 py-2 sm:px-6">
        <Button variant="link" className="h-auto p-0 text-sm font-normal" asChild>
          <Link href={listHref}>← Back to properties</Link>
        </Button>
      </div>

      <div className="overflow-x-hidden px-4 py-3 sm:px-6 sm:py-4">
        <h2 className="text-base font-semibold text-gray-900">Maintenance charges</h2>
        <p className="mt-1 text-sm text-gray-600">
          <span className="font-medium">{property.name}</span>
        </p>
        <p className="mt-2 text-xs leading-relaxed text-gray-500 sm:text-sm">
          Default maintenance for this property. Used when user billing is set to Standard.
        </p>
        <div className="mt-6">{fields}</div>
      </div>

      {actions}
    </div>
  );
}
