"use client";

import React, { useCallback, useEffect, useRef, useState } from "react";
import Link from "next/link";
import { useParams } from "next/navigation";
import { Button } from "@/components/ui/button";
import {
  Dialog,
  DialogContent,
  DialogHeader,
  DialogTitle,
} from "@/components/ui/dialog";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from "@/components/ui/select";
import { Textarea } from "@/components/ui/textarea";
import DataService from "@/config/axios";
import { getApiErrorMessage } from "@/lib/api-error";
import { tenantApiPath } from "@/lib/tenant-api";
import {
  uploadTenantFile,
  type TenantUploadedFile,
} from "@/lib/upload-tenant-file";
import { uploadTenantImageFile } from "@/lib/upload-tenant-image";
import { toast } from "sonner";
import { Paperclip, Trash2, User } from "lucide-react";
import ClientWorkspaceLayout from "./client-workspace-layout";

type TenantUserDetail = {
  _id: string;
  username: string;
  email: string;
  firstName?: string;
  lastName?: string;
  photo?: string;
  phone?: string;
  bio?: string;
  address?: string;
  status?: string;
  startDate?: string | null;
  endDate?: string | null;
  balance?: number;
  rent?: number;
  maintenance_fee?: number;
  maintenanceChargeMode?: "fixed" | "per_sqft";
  maintenanceChargeValue?: number;
  otherCharges?: number;
  billingDate?: string | null;
  maintenanceRatioType?: "standard" | "custom";
  attachments?: TenantUploadedFile[];
  spaceName?: string;
  spaceFloor?: string;
  spaceSize?: string;
  role?: { name?: string } | string | null;
  managementRole?: { name?: string } | string | null;
  linkedProperty?:
  | {
    name?: string;
    maintenanceChargeMode?: "fixed" | "per_sqft";
    maintenanceChargeValue?: number;
  }
  | string
  | null;
};

type SpaceOption = {
  unitId: string;
  propertyId: string;
  propertyName: string;
  /** Property `siteType` — Town plots do not use rent billing. */
  propertySiteType?: string;
  floorName: string;
  floorLevel?: number | null;
  officeName: string;
  size?: number | null;
  unitType?: string;
  plotZoning?: string;
  assignedToCurrentUser?: boolean;
};

function roleLabel(r: TenantUserDetail["role"]): string {
  if (!r) return "—";
  if (typeof r === "object" && r !== null && "name" in r && r.name) return String(r.name);
  return "—";
}

function dateInputValue(v?: string | null): string {
  if (!v) return "";
  const d = new Date(v);
  if (Number.isNaN(d.getTime())) return "";
  return d.toISOString().slice(0, 10);
}

function ClientUserDetailBody({
  tenantApiKey,
  tenantReady,
  userId,
  appSegment,
}: {
  tenantApiKey: string;
  tenantReady: boolean;
  userId: string;
  appSegment: string;
}) {
  const fileRef = useRef<HTMLInputElement>(null);
  const attachmentsRef = useRef<HTMLInputElement>(null);
  const [loading, setLoading] = useState(true);
  const [loadError, setLoadError] = useState<string | null>(null);
  const [saving, setSaving] = useState(false);
  const [photoUploading, setPhotoUploading] = useState(false);
  const [attachmentsUploading, setAttachmentsUploading] = useState(false);

  const [firstName, setFirstName] = useState("");
  const [lastName, setLastName] = useState("");
  const [email, setEmail] = useState("");
  const [phone, setPhone] = useState("");
  const [address, setAddress] = useState("");
  const [bio, setBio] = useState("");
  const [photo, setPhoto] = useState("");
  const [photoBroken, setPhotoBroken] = useState(false);
  const [username, setUsername] = useState("");
  const [status, setStatus] = useState("");
  const [roleName, setRoleName] = useState("—");
  const [startDate, setStartDate] = useState("");
  const [endDate, setEndDate] = useState("");
  const [balance, setBalance] = useState("0");
  const [rent, setRent] = useState("0");
  const [customMaintenanceChargeMode, setCustomMaintenanceChargeMode] = useState<
    "fixed" | "per_sqft"
  >("fixed");
  const [customMaintenanceChargeValue, setCustomMaintenanceChargeValue] = useState("0");
  const [standardMaintenanceChargeMode, setStandardMaintenanceChargeMode] = useState<
    "fixed" | "per_sqft"
  >("fixed");
  const [standardMaintenanceChargeValue, setStandardMaintenanceChargeValue] = useState("0");
  const [otherCharges, setOtherCharges] = useState("0");
  const [billingDate, setBillingDate] = useState("");
  const [maintenanceRatioType, setMaintenanceRatioType] = useState<"standard" | "custom">(
    "standard",
  );
  const [attachments, setAttachments] = useState<TenantUploadedFile[]>([]);
  const [spaceOptions, setSpaceOptions] = useState<SpaceOption[]>([]);
  const [selectedSpaceUnitIds, setSelectedSpaceUnitIds] = useState<string[]>([]);
  const [spaceModalOpen, setSpaceModalOpen] = useState(false);
  const [invoiceDownloading, setInvoiceDownloading] = useState(false);

  const load = useCallback(async () => {
    if (!tenantReady || !userId) return;
    setLoading(true);
    setLoadError(null);
    try {
      const [userRes, spacesRes] = await Promise.all([
        DataService.get(tenantApiPath(tenantApiKey, `/users/${encodeURIComponent(userId)}`)),
        DataService.get(
          tenantApiPath(tenantApiKey, `/users/${encodeURIComponent(userId)}/space-options`),
        ),
      ]);
      const u = userRes.data?.data as TenantUserDetail | undefined;
      const options = (spacesRes.data?.data as SpaceOption[] | undefined) || [];
      if (!u?._id) {
        setLoadError("User not found.");
        return;
      }
      setFirstName(u.firstName || "");
      setLastName(u.lastName || "");
      setEmail(u.email || "");
      setPhone(u.phone || "");
      setAddress(u.address || "");
      setBio(u.bio || "");
      setPhoto(u.photo || "");
      setPhotoBroken(false);
      setUsername(u.username || "");
      setStatus(u.status || "");
      setRoleName(roleLabel(u.role));
      setStartDate(dateInputValue(u.startDate));
      setEndDate(dateInputValue(u.endDate));
      setBalance(String(u.balance ?? 0));
      setRent(String(u.rent ?? 0));
      setCustomMaintenanceChargeMode(u.maintenanceChargeMode === "per_sqft" ? "per_sqft" : "fixed");
      setCustomMaintenanceChargeValue(String(u.maintenanceChargeValue ?? 0));
      setOtherCharges(String(u.otherCharges ?? 0));
      setBillingDate(dateInputValue(u.billingDate));
      const ratioType = u.maintenanceRatioType === "custom" ? "custom" : "standard";
      setMaintenanceRatioType(ratioType);
      if (u.linkedProperty && typeof u.linkedProperty === "object") {
        setStandardMaintenanceChargeMode(
          u.linkedProperty.maintenanceChargeMode === "per_sqft" ? "per_sqft" : "fixed"
        );
        setStandardMaintenanceChargeValue(String(u.linkedProperty.maintenanceChargeValue ?? 0));
      } else {
        setStandardMaintenanceChargeMode("fixed");
        setStandardMaintenanceChargeValue("0");
      }
      setAttachments(Array.isArray(u.attachments) ? u.attachments : []);
      setSpaceOptions(options);
      setSelectedSpaceUnitIds(
        options.filter((o) => o.assignedToCurrentUser).map((o) => String(o.unitId)),
      );
    } catch (e: unknown) {
      const msg = getApiErrorMessage(e, "Could not load user");
      setLoadError(msg);
    } finally {
      setLoading(false);
    }
  }, [tenantApiKey, tenantReady, userId]);

  useEffect(() => {
    void load();
  }, [load]);

  const onPhotoFiles = async (files: FileList | null) => {
    const f = files?.[0];
    if (!f || !tenantReady) return;
    setPhotoUploading(true);
    try {
      const url = await uploadTenantImageFile(tenantApiKey, f);
      setPhoto(url);
      setPhotoBroken(false);
      toast.success("Photo uploaded — save to apply");
    } catch (e: unknown) {
      toast.error(getApiErrorMessage(e, "Upload failed"));
    } finally {
      setPhotoUploading(false);
    }
  };

  const onAttachmentFiles = async (files: FileList | null) => {
    if (!files?.length || !tenantReady) return;
    const picked = Array.from(files);
    const allowed = new Set(["image/png", "image/jpeg", "image/jpg", "image/webp", "image/gif", "application/pdf"]);
    const invalid = picked.find((f) => !allowed.has(f.type));
    if (invalid) {
      toast.error("Only images and PDF files are allowed");
      return;
    }
    setAttachmentsUploading(true);
    try {
      const uploaded = await Promise.all(
        picked.map((f) => uploadTenantFile(tenantApiKey, f)),
      );
      setAttachments((prev) => [...prev, ...uploaded]);
      toast.success(`${uploaded.length} attachment(s) uploaded`);
    } catch (e: unknown) {
      toast.error(getApiErrorMessage(e, "Attachment upload failed"));
    } finally {
      setAttachmentsUploading(false);
    }
  };

  const removeAttachment = (index: number) => {
    setAttachments((prev) => prev.filter((_, i) => i !== index));
  };

  const submit = async () => {
    if (!firstName.trim() || !lastName.trim() || !email.trim()) {
      toast.error("First name, last name, and email are required");
      return;
    }
    const balanceNum = Number(balance || 0);
    const standardChargeValueNum = Number(standardMaintenanceChargeValue || 0);
    const customChargeValueNum = Number(customMaintenanceChargeValue || 0);
    const otherChargesNum = Number(otherCharges || 0);
    const billingDateValue = billingDate || null;
    const isOwnerRole = roleName.trim().toLowerCase() === "owner";
    const assignedForBilling = spaceOptions.filter((o) =>
      selectedSpaceUnitIds.includes(o.unitId),
    );
    const primarySpace = assignedForBilling[0];
    const primarySpaceIsTown =
      primarySpace != null && String(primarySpace.propertySiteType || "") === "town";
    const rentNum =
      isOwnerRole || primarySpaceIsTown ? 0 : Number(rent || 0);
    const primaryAssignedSize = Number(primarySpace?.size ?? 0);
    const safeAssignedSize = Number.isFinite(primaryAssignedSize) ? primaryAssignedSize : 0;
    const selectedMode =
      maintenanceRatioType === "custom" ? customMaintenanceChargeMode : standardMaintenanceChargeMode;
    const selectedValue =
      maintenanceRatioType === "custom" ? customChargeValueNum : standardChargeValueNum;
    if (!Number.isFinite(selectedValue)) {
      toast.error("Maintenance charge value must be a number");
      return;
    }
    const maintenanceFeeNum =
      selectedMode === "per_sqft" ? selectedValue * safeAssignedSize : selectedValue;

    if (
      !Number.isFinite(balanceNum) ||
      !Number.isFinite(maintenanceFeeNum) ||
      !Number.isFinite(otherChargesNum) ||
      !Number.isFinite(rentNum)
    ) {
      toast.error("Balance, rent, maintenance_fee, and other charges must be numbers");
      return;
    }
    setSaving(true);
    try {
      await DataService.patch(tenantApiPath(tenantApiKey, `/users/${encodeURIComponent(userId)}`), {
        firstName: firstName.trim(),
        lastName: lastName.trim(),
        email: email.trim(),
        phone: phone.trim(),
        address: address.trim(),
        bio: bio.trim(),
        photo: photo.trim(),
        startDate: startDate || null,
        endDate: endDate || null,
        balance: balanceNum,
        rent: rentNum,
        maintenance_fee: maintenanceFeeNum,
        maintenanceChargeMode: selectedMode,
        maintenanceChargeValue: selectedValue,
        otherCharges: otherChargesNum,
        billingDate: billingDateValue,
        maintenanceRatioType,
        attachments,
        spaceUnitIds: selectedSpaceUnitIds,
      });
      toast.success("Profile updated");
      await load();
    } catch (e: unknown) {
      toast.error(getApiErrorMessage(e, "Could not save"));
    } finally {
      setSaving(false);
    }
  };

  const downloadInvoice = async () => {
    setInvoiceDownloading(true);
    try {
      const { jsPDF } = await import("jspdf");
      const balanceNum = Number(balance || 0);
      const assignedForInv = spaceOptions.filter((o) => selectedSpaceUnitIds.includes(o.unitId));
      const primaryInv = assignedForInv[0];
      const invTown =
        primaryInv != null && String(primaryInv.propertySiteType || "") === "town";
      const rentNum = invTown ? 0 : Number(rent || 0);
      const otherChargesNum = Number(otherCharges || 0);
      const standardChargeValueNum = Number(standardMaintenanceChargeValue || 0);
      const customChargeValueNum = Number(customMaintenanceChargeValue || 0);
      const primaryAssignedSize = Number(primaryAssignedSpace?.size ?? 0);
      const safeAssignedSize = Number.isFinite(primaryAssignedSize) ? primaryAssignedSize : 0;
      const selectedMode =
        maintenanceRatioType === "custom" ? customMaintenanceChargeMode : standardMaintenanceChargeMode;
      const selectedValue =
        maintenanceRatioType === "custom" ? customChargeValueNum : standardChargeValueNum;
      const maintenanceFeeNum =
        selectedMode === "per_sqft" ? selectedValue * safeAssignedSize : selectedValue;
      const totalDue = balanceNum + rentNum + maintenanceFeeNum + otherChargesNum;
      const displayName =
        [firstName, lastName].filter(Boolean).join(" ").trim() || username || "User";
      const invoiceNo = `INV-${Date.now()}`;
      const issuedOn = new Date().toISOString().slice(0, 10);

      const doc = new jsPDF({ unit: "pt", format: "a4" });
      let y = 56;
      doc.setFont("helvetica", "bold");
      doc.setFontSize(18);
      doc.text("Invoice", 40, y);
      y += 28;
      doc.setFont("helvetica", "normal");
      doc.setFontSize(11);
      doc.text(`Invoice #: ${invoiceNo}`, 40, y);
      y += 18;
      doc.text(`Date: ${issuedOn}`, 40, y);
      y += 18;
      doc.text(`Customer: ${displayName} (${email})`, 40, y);
      y += 28;
      doc.setFont("helvetica", "bold");
      doc.text("Item", 40, y);
      doc.text("Amount", 510, y, { align: "right" });
      y += 10;
      doc.setLineWidth(0.5);
      doc.line(40, y, 555, y);
      y += 18;
      doc.setFont("helvetica", "normal");

      const rows: Array<{ label: string; value: number }> = [
        { label: "Balance", value: balanceNum },
        { label: "Rent", value: rentNum },
        {
          label: `Maintenance (${selectedMode === "per_sqft" ? "Per Sq Feet" : "Fixed"})`,
          value: maintenanceFeeNum,
        },
        { label: "Other Charges", value: otherChargesNum },
      ];

      rows.forEach((row) => {
        doc.text(row.label, 40, y);
        doc.text(row.value.toFixed(2), 510, y, { align: "right" });
        y += 18;
      });

      y += 4;
      doc.setLineWidth(0.5);
      doc.line(40, y, 555, y);
      y += 20;
      doc.setFont("helvetica", "bold");
      doc.text("Total", 40, y);
      doc.text(totalDue.toFixed(2), 510, y, { align: "right" });

      doc.save(`${displayName.replace(/\s+/g, "-").toLowerCase() || "user"}-invoice.pdf`);
    } catch (e: unknown) {
      toast.error(getApiErrorMessage(e, "Could not generate invoice PDF"));
    } finally {
      setInvoiceDownloading(false);
    }
  };

  const backHref = `/${appSegment}/users`;

  if (loading) {
    return (
      <div className="rounded-md border bg-white p-8 text-center text-gray-500">Loading…</div>
    );
  }

  if (loadError) {
    return (
      <div className="space-y-4 rounded-md border border-amber-200 bg-amber-50 p-6 text-sm text-amber-950">
        <p>{loadError}</p>
        <Button variant="outline" size="sm" asChild>
          <Link href={backHref}>Back to users</Link>
        </Button>
      </div>
    );
  }

  const displayPhoto = photo.trim() !== "" && !photoBroken ? photo.trim() : null;
  const assignedSpaces = spaceOptions.filter((o) => selectedSpaceUnitIds.includes(o.unitId));
  const availableSpaces = spaceOptions.filter(
    (o) => !o.assignedToCurrentUser && !selectedSpaceUnitIds.includes(o.unitId),
  );
  const primaryAssignedSpace = assignedSpaces.length > 0 ? assignedSpaces[0] : null;
  const ownedByValue = primaryAssignedSpace ? roleName : "";
  const assignedName = primaryAssignedSpace ? primaryAssignedSpace.officeName : "";
  const assignedFloor =
    primaryAssignedSpace != null
      ? (primaryAssignedSpace.floorName?.trim() ||
        (primaryAssignedSpace.floorLevel != null ? `Floor ${primaryAssignedSpace.floorLevel}` : ""))
      : "";
  const assignedSize =
    primaryAssignedSpace != null && primaryAssignedSpace.size != null
      ? String(primaryAssignedSpace.size)
      : "";
  const billingHideRentForTownPlots =
    primaryAssignedSpace != null &&
    String(primaryAssignedSpace.propertySiteType || "") === "town";

  return (
    <div className="space-y-6">
      <div className="flex flex-wrap justify-end gap-2">
        <Button
          type="button"
          variant="outline"
          onClick={() => void downloadInvoice()}
          disabled={invoiceDownloading}
        >
          {invoiceDownloading ? "Preparing PDF…" : "Download invoice"}
        </Button>
        <Button type="button" onClick={() => void submit()} disabled={saving}>
          {saving ? "Saving…" : "Save changes"}
        </Button>
        <Button variant="outline" type="button" asChild>
          <Link href={backHref}>Cancel</Link>
        </Button>
      </div>

      <div className="rounded-lg border border-gray-200 bg-white p-4 shadow-sm sm:p-6">
        <h2 className="text-lg font-semibold text-gray-900">User Account</h2>
        <p className="mt-1 text-sm text-gray-500">
          Update this member&apos;s profile, contact details, and photo. Role and access changes stay
          on the Users list (edit).
        </p>

        <div className="mt-6 flex flex-col gap-6 lg:flex-row">
          <div className="flex flex-col items-start gap-3">
            <Label className="text-gray-700">Profile photo</Label>
            <div className="flex flex-col items-start gap-3">
              {displayPhoto ? (
                // eslint-disable-next-line @next/next/no-img-element -- API-hosted URL
                <img
                  src={displayPhoto}
                  alt=""
                  className="size-24 rounded-full border border-gray-200 object-cover"
                  onError={() => setPhotoBroken(true)}
                />
              ) : (
                <div className="flex size-24 items-center justify-center rounded-full border border-dashed border-gray-300 bg-gray-50 text-gray-400">
                  <User className="size-10" aria-hidden />
                </div>
              )}
              <div className="flex flex-col gap-2">
                <input
                  ref={fileRef}
                  type="file"
                  className="hidden"
                  accept="image/png,image/jpeg,image/jpg,image/webp,image/gif"
                  onChange={(e) => void onPhotoFiles(e.target.files)}
                />
                <Button
                  type="button"
                  variant="outline"
                  size="sm"
                  disabled={photoUploading}
                  onClick={() => fileRef.current?.click()}
                >
                  {photoUploading ? "Uploading…" : displayPhoto ? "Replace photo" : "Upload photo"}
                </Button>
                {displayPhoto ? (
                  <Button
                    type="button"
                    variant="ghost"
                    size="sm"
                    className="text-red-600 hover:text-red-700"
                    onClick={() => {
                      setPhoto("");
                      setPhotoBroken(false);
                    }}
                  >
                    Remove photo
                  </Button>
                ) : null}
              </div>
            </div>
          </div>

          <div className="grid min-w-0 flex-1 gap-4 sm:grid-cols-2">
            <div>
              <Label htmlFor="ud-fn">First name</Label>
              <Input
                id="ud-fn"
                value={firstName}
                onChange={(e) => setFirstName(e.target.value)}
                className="mt-1"
              />
            </div>
            <div>
              <Label htmlFor="ud-ln">Last name</Label>
              <Input
                id="ud-ln"
                value={lastName}
                onChange={(e) => setLastName(e.target.value)}
                className="mt-1"
              />
            </div>
            <div className="sm:col-span-2">
              <Label htmlFor="ud-em">Email</Label>
              <Input
                id="ud-em"
                type="email"
                value={email}
                onChange={(e) => setEmail(e.target.value)}
                className="mt-1"
              />
            </div>
            <div>
              <Label htmlFor="ud-un">Username</Label>
              <Input id="ud-un" value={username} readOnly className="mt-1 bg-gray-50" />
            </div>
            <div>
              <Label htmlFor="ud-st">Status</Label>
              <Input id="ud-st" value={status} readOnly className="mt-1 bg-gray-50" />
            </div>
            <div className="sm:col-span-2">
              <Label htmlFor="ud-ph">Phone</Label>
              <Input
                id="ud-ph"
                type="tel"
                value={phone}
                onChange={(e) => setPhone(e.target.value)}
                className="mt-1"
              />
            </div>
            <div className="sm:col-span-2">
              <Label htmlFor="ud-ad">Address</Label>
              <Textarea
                id="ud-ad"
                value={address}
                onChange={(e) => setAddress(e.target.value)}
                className="mt-1 min-h-[88px] resize-y"
              />
            </div>
            {/* <div className="sm:col-span-2">
              <Label htmlFor="ud-bio">Bio</Label>
              <Textarea
                id="ud-bio"
                value={bio}
                onChange={(e) => setBio(e.target.value)}
                className="mt-1 min-h-[88px] resize-y"
              />
            </div> */}
          </div>
        </div>

      </div>

      <div className="rounded-lg border border-gray-200 bg-white p-4 shadow-sm sm:p-6">
        <h2 className="text-lg font-semibold text-gray-900">User Account - Billing & Attachments</h2>
        <p className="mt-1 text-sm text-gray-500">
          Add optional period dates, charges, maintenance settings, and multiple image/PDF attachments.
        </p>
        <div className="mt-5 grid gap-4 sm:grid-cols-2">
          <div>
            <Label htmlFor="ud-sd">Start date (optional)</Label>
            <Input
              id="ud-sd"
              type="date"
              value={startDate}
              onChange={(e) => setStartDate(e.target.value)}
              className="mt-1"
            />
          </div>
          <div>
            <Label htmlFor="ud-ed">End date (optional)</Label>
            <Input
              id="ud-ed"
              type="date"
              value={endDate}
              onChange={(e) => setEndDate(e.target.value)}
              className="mt-1"
            />
          </div>
          <div>
            <Label htmlFor="ud-bal">Balance</Label>
            <Input
              id="ud-bal"
              type="number"
              step="0.01"
              value={balance}
              onChange={(e) => setBalance(e.target.value)}
              className="mt-1"
            />
          </div>
          {roleName.trim().toLowerCase() === "owner" ? (
            <div>
              <Label>Rent</Label>
              <Input value="Not applicable for Owner role" readOnly className="mt-1 bg-gray-50" />
            </div>
          ) : billingHideRentForTownPlots ? (
            <div>
              <Label>Rent</Label>
              <Input
                value="Not used for Town plot assignments"
                readOnly
                className="mt-1 bg-gray-50"
              />
            </div>
          ) : (
            <div>
              <Label htmlFor="ud-rent">Rent</Label>
              <Input
                id="ud-rent"
                type="number"
                step="0.01"
                value={rent}
                onChange={(e) => setRent(e.target.value)}
                className="mt-1"
              />
            </div>
          )}
          <div>
            <Label htmlFor="ud-oc">Other charges</Label>
            <Input
              id="ud-oc"
              type="number"
              step="0.01"
              value={otherCharges}
              onChange={(e) => setOtherCharges(e.target.value)}
              className="mt-1"
            />
          </div>
          <div>
            <Label htmlFor="ud-bd">Billing date</Label>
            <Input
              id="ud-bd"
              type="date"
              value={billingDate}
              onChange={(e) => setBillingDate(e.target.value)}
              className="mt-1"
            />
          </div>
          <div>
            <Label>Maintenance</Label>
            <Select value={maintenanceRatioType} onValueChange={(v) => setMaintenanceRatioType(v as "standard" | "custom")}>
              <SelectTrigger className="mt-1">
                <SelectValue placeholder="Select ratio type" />
              </SelectTrigger>
              <SelectContent>
                <SelectItem value="standard">Standard</SelectItem>
                <SelectItem value="custom">Custom</SelectItem>
              </SelectContent>
            </Select>
          </div>
          {maintenanceRatioType === "standard" ? (
            <div className="sm:col-span-2 rounded-md border border-blue-100 bg-blue-50 p-3">
              <p className="text-xs text-blue-900">
                Standard mode uses linked property maintenance charges.
              </p>
              <div className="mt-2 grid gap-2 sm:grid-cols-2">
                <p className="text-sm text-gray-700">
                  Type:{" "}
                  <strong>{standardMaintenanceChargeMode === "per_sqft" ? "One Per Sq Feet" : "One Fixed"}</strong>
                </p>
                <p className="text-sm text-gray-700">
                  Value: <strong>{standardMaintenanceChargeValue || "0"}</strong>
                </p>
              </div>
            </div>
          ) : null}
          {maintenanceRatioType === "custom" ? (
            <div className="sm:col-span-2 space-y-3 rounded-md border border-gray-200 p-3">
              <Label>Custom maintenance 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="user-custom-maintenance-mode"
                    checked={customMaintenanceChargeMode === "fixed"}
                    onChange={() => setCustomMaintenanceChargeMode("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="user-custom-maintenance-mode"
                    checked={customMaintenanceChargeMode === "per_sqft"}
                    onChange={() => setCustomMaintenanceChargeMode("per_sqft")}
                  />
                  One Per Sq Feet
                </label>
              </div>
              <Label htmlFor="ud-main-fee">
                {customMaintenanceChargeMode === "fixed"
                  ? "Custom fixed value"
                  : "Custom per sq feet value"}
              </Label>
              <Input
                id="ud-main-fee"
                type="number"
                step="0.01"
                value={customMaintenanceChargeValue}
                onChange={(e) => setCustomMaintenanceChargeValue(e.target.value)}
                className="mt-1"
              />
            </div>
          ) : null}
          <div className="sm:col-span-2">
            <div className="flex items-center justify-between gap-2">
              <Label>Attachments (multiple)</Label>
              <input
                ref={attachmentsRef}
                type="file"
                multiple
                className="hidden"
                accept="image/png,image/jpeg,image/jpg,image/webp,image/gif,application/pdf"
                onChange={(e) => {
                  void onAttachmentFiles(e.target.files);
                  e.target.value = "";
                }}
              />
              <Button
                type="button"
                variant="outline"
                size="sm"
                disabled={attachmentsUploading}
                onClick={() => attachmentsRef.current?.click()}
              >
                <Paperclip className="mr-2 size-4" />
                {attachmentsUploading ? "Uploading…" : "Add attachments"}
              </Button>
            </div>
            {attachments.length > 0 ? (
              <div className="mt-3 space-y-2">
                {attachments.map((a, idx) => (
                  <div
                    key={`${a.url}-${idx}`}
                    className="flex items-center justify-between rounded-md border border-gray-200 px-3 py-2 text-sm"
                  >
                    <a
                      href={a.url}
                      target="_blank"
                      rel="noreferrer"
                      className="max-w-[75%] truncate text-primary underline underline-offset-2"
                    >
                      {a.name || `Attachment ${idx + 1}`}
                    </a>
                    <Button
                      type="button"
                      variant="ghost"
                      size="icon"
                      className="size-7 text-red-600 hover:text-red-700"
                      onClick={() => removeAttachment(idx)}
                    >
                      <Trash2 className="size-4" />
                    </Button>
                  </div>
                ))}
              </div>
            ) : (
              <p className="mt-2 text-xs text-gray-500">No attachments added yet.</p>
            )}
          </div>
        </div>
      </div>

      <div className="rounded-lg border border-gray-200 bg-white p-4 shadow-sm sm:p-6">
        <div className="flex flex-wrap items-start justify-between gap-2">
          <div>
            <h2 className="text-lg font-semibold text-gray-900">Space Details</h2>
            <p className="mt-1 text-sm text-gray-500">Assign space from modal only.</p>
          </div>
          <div className="flex gap-2">
            <Button type="button" onClick={() => setSpaceModalOpen(true)}>
              Assign Space
            </Button>
          </div>
        </div>
        {/* <div className="mt-4 grid gap-4 sm:grid-cols-2">
          <div>
            <Label htmlFor="ud-space-owned-by">Owned By</Label>
            <Input
              id="ud-space-owned-by"
              value={ownedByValue}
              readOnly
              className="mt-1"
            />
          </div>
          <div>
            <Label htmlFor="ud-space-name">Name</Label>
            <Input
              id="ud-space-name"
              value={assignedName}
              readOnly
              className="mt-1"
              placeholder="Assigned office"
            />
          </div>
          <div>
            <Label htmlFor="ud-space-floor">Floor</Label>
            <Input
              id="ud-space-floor"
              value={assignedFloor}
              readOnly
              className="mt-1"
              placeholder="Assigned floor"
            />
          </div>
          <div >
            <Label htmlFor="ud-space-size">Size</Label>
            <Input
              id="ud-space-size"
              value={assignedSize}
              readOnly
              className="mt-1"
              placeholder="Assigned size"
            />
          </div>
        </div> */}
        <div className="mt-5 rounded-md border border-gray-200 p-3">
          <div className="flex items-center justify-between">
            <p className="text-sm font-medium text-gray-900">Assigned spaces</p>
            <p className="text-sm font-medium text-gray-900">Owned By: {roleName}</p>
          </div>
          {assignedSpaces.length === 0 ? (
            <p className="mt-2 text-sm text-gray-500">No space assigned yet.</p>
          ) : (
            <div className="mt-3 space-y-2">
              {assignedSpaces.map((opt) => {
                const floorText =
                  opt.floorName?.trim() ||
                  (opt.floorLevel != null ? `Floor ${opt.floorLevel}` : "Floor");
                const sizeText = opt.size != null ? `${opt.size}` : "—";
                const label = `${opt.propertyName} - ${floorText} - ${opt.officeName}`;
                return (
                  <div
                    key={`assigned-${opt.unitId}`}
                    className="flex items-center justify-between rounded border border-gray-200 px-3 py-2"
                  >
                    <div className="min-w-0 text-sm">
                      <p className="truncate font-medium text-gray-900">{label}</p>
                      <p className="text-xs text-gray-500">
                        Type: {opt.unitType || "—"} | Size: {sizeText}
                      </p>
                    </div>
                    <Button
                      type="button"
                      variant="outline"
                      size="sm"
                      className="text-red-600 hover:text-red-700"
                      onClick={() =>
                        setSelectedSpaceUnitIds((prev) =>
                          prev.filter((id) => id !== opt.unitId),
                        )
                      }
                    >
                      In active
                    </Button>
                  </div>
                );
              })}
            </div>
          )}
        </div>
      </div>

      <Dialog open={spaceModalOpen} onOpenChange={setSpaceModalOpen}>
        <DialogContent className="max-h-[min(90vh,100dvh)] max-w-2xl overflow-y-auto">
          <DialogHeader>
            <DialogTitle>Assign Space</DialogTitle>
          </DialogHeader>
          {availableSpaces.length === 0 ? (
            <p className="text-sm text-gray-500">No unassigned office available right now.</p>
          ) : (
            <div className="space-y-2">
              {availableSpaces.map((opt) => {
                const floorText =
                  opt.floorName?.trim() ||
                  (opt.floorLevel != null ? `Floor ${opt.floorLevel}` : "Floor");
                const sizeText = opt.size != null ? `${opt.size}` : "—";
                const label = `${opt.propertyName} - ${floorText} - ${opt.officeName}`;
                return (
                  <div
                    key={opt.unitId}
                    className="flex items-center justify-between rounded border border-gray-200 px-3 py-2"
                  >
                    <div className="min-w-0 text-sm">
                      <p className="truncate font-medium text-gray-900">{label}</p>
                      <p className="text-xs text-gray-500">
                        Type: {opt.unitType || "—"} | Size: {sizeText}
                      </p>
                    </div>
                    <Button
                      type="button"
                      size="sm"
                      onClick={() => {
                        setSelectedSpaceUnitIds((prev) =>
                          prev.includes(opt.unitId) ? prev : [...prev, opt.unitId],
                        );
                        setSpaceModalOpen(false);
                      }}
                    >
                      Assign
                    </Button>
                  </div>
                );
              })}
            </div>
          )}
        </DialogContent>
      </Dialog>
    </div>
  );
}

export default function ClientUserDetail() {
  const { app, userId } = useParams() as { app: string; userId: string };
  const id = userId ? decodeURIComponent(userId) : "";

  return (
    <ClientWorkspaceLayout
      title="Member profile"
      barDescription="Edit profile and contact information. Space details will be expanded in a later step."
      actions={(ctx) => (
        <Button variant="outline" size="sm" className="w-full md:w-auto" asChild>
          <Link href={`/${app}/users`}>Back to users</Link>
        </Button>
      )}
    >
      {(ctx) =>
        !id ? (
          <p className="text-sm text-gray-500">Invalid user.</p>
        ) : (
          <ClientUserDetailBody
            tenantApiKey={ctx.tenantApiKey}
            tenantReady={ctx.tenantReady}
            userId={id}
            appSegment={app}
          />
        )
      }
    </ClientWorkspaceLayout>
  );
}
