import {
  Dialog,
  DialogContent,
  DialogHeader,
  DialogTitle,
} from "@/shared/common/ui/dialog";
import { Loader2 } from "lucide-react";
import { EditUnitForm } from "../forms/EditUnitForm";
import { UnitDto } from "@/user-management/dto/unit/unitDto";
import { useUnit } from "@/user-management/hooks/useUnit";

interface UnitDialogProps {
  isOpen: boolean;
  onClose: () => void;
  units: UnitDto[];
  unitId: string;
}

export function EditUnitDialog({
  isOpen,
  onClose,
  units,
  unitId,
}: UnitDialogProps) {
  const handleSuccess = () => {
    onClose();
  };
  const fromList = units?.find((p) => p.id === unitId);
  // Related units (from /units/child-units/...) aren't in the top-level list,
  // so fetch by id when we don't already have the full record.
  const { getById } = useUnit();
  const { data: byIdResp, isLoading } = getById(fromList ? "" : unitId);
  const fetched = (byIdResp?.data ?? null) as UnitDto | null;
  const currentUnit = fromList ?? fetched;

  return (
    <Dialog open={isOpen} onOpenChange={(open) => !open && onClose()}>
      <DialogContent className="min-w-0 overflow-hidden sm:max-w-[425px]">
        <DialogHeader className="min-w-0">
          <DialogTitle className="max-w-full break-words pr-6 [overflow-wrap:anywhere]">
            Edit Unit {currentUnit?.name?.en}
          </DialogTitle>
        </DialogHeader>
        {!currentUnit ? (
          <div className="flex justify-center py-6">
            {isLoading ? (
              <Loader2 className="h-5 w-5 animate-spin text-gray-500" />
            ) : (
              <span className="text-sm text-gray-500">Unit not found.</span>
            )}
          </div>
        ) : (
          <EditUnitForm
            unit={currentUnit}
            onSuccess={handleSuccess}
            onCancel={onClose}
          />
        )}
      </DialogContent>
    </Dialog>
  );
}
